2011-07-04 199 views
7

我试图在HTML画布中绘制弯曲的箭头。我没有问题绘制曲线,但我不知道如何将>放在线的末端(方向)。HTML画布 - 绘制弯曲的箭头

ctx.beginPath(); 
    ctx.fillStyle = "rgba(55, 217, 56,"+ opacity +")"; 
    ctx.moveTo(this.fromX,this.fromY); 
    ctx.quadraticCurveTo(this.controlX, this.controlY, this.toX, this.toY); 
ctx.stroke(); 

我的想法是在最后一小部分线上画一个三角形。 如何获得线中点的坐标?

下面是更好地理解的图像。

Curve with arrow

回答

15

由于您使用的是二次曲线,你知道两点,使的是,在你的箭头的“方向”指向一个行:

enter image description here

于是扔下一触即发,你有自己的解决方案。这里是一个广义函数会为你做它:

http://jsfiddle.net/SguzM/

function drawArrowhead(locx, locy, angle, sizex, sizey) { 
    var hx = sizex/2; 
    var hy = sizey/2; 

    ctx.translate((locx), (locy)); 
    ctx.rotate(angle); 
    ctx.translate(-hx,-hy); 

    ctx.beginPath(); 
    ctx.moveTo(0,0); 
    ctx.lineTo(0,1*sizey);  
    ctx.lineTo(1*sizex,1*hy); 
    ctx.closePath(); 
    ctx.fill(); 

    ctx.translate(hx,hy); 
    ctx.rotate(-angle); 
    ctx.translate(-locx,-locy); 
}   

// returns radians 
function findAngle(sx, sy, ex, ey) { 
    // make sx and sy at the zero point 
    return Math.atan2((ey - sy), (ex - sx)); 
} 
+5

+1,只改变我做了这里:http://jsfiddle.net/SguzM/1/是改变使用的'反正切'atan2'来支持负角度并防止零除。 – Variant

+0

啊,好想! –

+0

非常好谢谢你俩 – deep