10

我正在尝试在 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();

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

下图是为了更好的理解。

带箭头的曲线

4

1 回答 1

18

由于您使用的是二次曲线,因此您知道有两个点构成一条指向箭头“方向”的线:

在此处输入图像描述

所以扔掉一点三角,你自己就有了解决方案。这是一个通用的函数,可以为你做这件事:

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));
}
于 2011-07-05T02:09:37.427 回答