Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Canvas - Draw curved arrows

I'm trying to draw curved arrows in a html canvas. I have no problem to draw a curved line but I don't know how to put the > at the end of the line (direction).

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();

My idea is taking a small part of the line at the end and draw a triangle. How can I get the coordinate of a point in the line?

Below is the image for better understanding.

Curve with arrow

like image 726
deep Avatar asked Jul 04 '11 23:07

deep


1 Answers

Since you're using a quadratic curve, you know two points that make a line that points in the "direction" of your arrow head:

enter image description here

So throw down a smidge of trig and you have yourself a solution. Here's a generalized function that will do it for you:

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));
}
like image 64
Simon Sarris Avatar answered Sep 22 '22 21:09

Simon Sarris