2015-01-05 132 views
2

我有一個二次曲線,我想在末尾繪製箭頭。我有這樣的代碼:在HTML5畫布二次曲線上繪製箭頭

http://jsfiddle.net/ju2jh84d/3/

var ctx = document.getElementById('arrowCanvas').getContext('2d'); 
 

 
var startPointX = 55; 
 
var startPointY = 50; 
 
var endPointX = 108; 
 
var endPointY = 118; 
 
ctx.strokeStyle = "rgb(0,0,255)"; 
 
ctx.lineWidth = 3; 
 
var x = (startPointX + endPointX)/2; 
 
var y = (startPointY + endPointY)/2; 
 
var le = (endPointY - endPointY)/(startPointX - endPointX); 
 
var angle = Math.atan(le); 
 
var sx = Math.pow((startPointX - endPointX), 2); 
 
var sy = Math.pow((endPointY - endPointY), 2); 
 
var d = Math.sqrt(sx + sy)/2; 
 

 
var px = x - d * Math.sin(angle); 
 
var py = y + d * Math.cos(angle); 
 

 
var arrowAngle = Math.atan2(x - endPointX, y - endPointY); 
 
var arrowWidth = 20; 
 

 
ctx.beginPath(); 
 
ctx.moveTo(startPointX, startPointY); 
 
ctx.quadraticCurveTo(px, py, endPointX, endPointY); 
 
ctx.lineTo(endPointX - arrowWidth * Math.sin(arrowAngle - Math.PI/6), endPointY - arrowWidth * Math.cos(arrowAngle - Math.PI/6)); 
 
ctx.moveTo(endPointX, endPointY); 
 
ctx.lineTo(endPointX - arrowWidth * Math.sin(arrowAngle + Math.PI/6), endPointY - arrowWidth * Math.cos(arrowAngle + Math.PI/6)); 
 
ctx.stroke(); 
 
ctx.closePath();
<canvas id="arrowCanvas"></canvas>

不過,雖然我可以得出一個很好的箭頭,它正確不是傾斜的。我在這段代碼中做錯了什麼?

+1

'變種SY = Math.pow((endPointY - endPointY),2);'這是一個錯誤? – rafaelcastrocouto

+1

是的,但將其更改爲startPointY - endPointY不能解決問題。感謝您的提升! – ohyeah

回答

2

使用二次點對準:

var ctx = document.getElementById('arrowCanvas').getContext('2d'); 
 

 
var startPointX = 50; 
 
var startPointY = 10; 
 
var endPointX = 100; 
 
var endPointY = 120; 
 
var quadPointX = 35; 
 
var quadPointY = 70; 
 

 
ctx.strokeStyle = "rgb(0,0,255)"; 
 
ctx.lineWidth = 3; 
 

 
var arrowAngle = Math.atan2(quadPointX - endPointX, quadPointY - endPointY) + Math.PI; 
 
var arrowWidth = 20; 
 

 
ctx.beginPath(); 
 
ctx.moveTo(startPointX, startPointY); 
 

 
ctx.quadraticCurveTo(quadPointX, quadPointY, endPointX, endPointY); 
 
//ctx.lineTo(endPointX, endPointY); 
 

 
ctx.moveTo(endPointX - (arrowWidth * Math.sin(arrowAngle - Math.PI/6)), 
 
      endPointY - (arrowWidth * Math.cos(arrowAngle - Math.PI/6))); 
 

 
ctx.lineTo(endPointX, endPointY); 
 

 
ctx.lineTo(endPointX - (arrowWidth * Math.sin(arrowAngle + Math.PI/6)), 
 
      endPointY - (arrowWidth * Math.cos(arrowAngle + Math.PI/6))); 
 

 
ctx.stroke(); 
 
ctx.closePath();
<canvas id="arrowCanvas"></canvas>

+1

很好,謝謝! – ohyeah

+1

Upvote分配箭頭角度=== quadPoint到endPoint的角度。 – markE