Search code examples
javascriptcanvascreatejs

How to draw a curved arrow using CreateJS?


JavaScript code for drawing curved arrow is already available in this fiddle: http://jsfiddle.net/SguzM/

I want to do the same thing using the CreateJS library.

Code from the above fiddle is below:

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

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


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

var sx = 50;
var sy = 190;
var ex = 100;
var ey = 10;

ctx.beginPath();
ctx.fillStyle = "rgba(55, 217, 56,1)";
ctx.moveTo(10,10);
ctx.quadraticCurveTo(sx, sy, ex, ey);
ctx.stroke();

var ang = findAngle(sx, sy, ex, ey);
ctx.fillRect(ex, ey, 2, 2);
drawArrowhead(ex, ey, ang, 12, 12);

Solution

  • In CreateJS, Graphics class provides arc/arcTo, bezierCurveTo, and quadraticCurveTo methods for drawing curved line.

    You can easily calculate a slope's radian value by using Math.atan2(y, x). In CreateJS rotation property uses degree, so convert the radian value to degree and rotate arrow by the degree value.

    This is jsfiddle: http://jsfiddle.net/10rceqj5/1/

    JavaScript:

    var stage = new createjs.Stage("demoCanvas");
    drawingCanvas = new createjs.Shape();
    stage.addChild(drawingCanvas);
    drawingCanvas.graphics.setStrokeStyle(1).beginStroke(createjs.Graphics.getRGB(0,0,0)).moveTo(10, 10).curveTo(50, 190, 90, 10);
    drawArrow(Math.atan2((10 - 190), (90 - 50)), 90, 10);
    
    drawingCanvas.graphics.moveTo(10, 110).bezierCurveTo(10, 240, 90, 240, 90, 110);
    drawArrow(Math.atan2((110 - 240), (90 - 90)), 90, 110);
    
    drawingCanvas.graphics.moveTo(10, 210).quadraticCurveTo(50, 390, 90, 210);
    drawArrow(Math.atan2((210 - 390), (90 - 50)), 90, 210);
    stage.update();
    
    
    function drawArrow(radian, x, y) {
        var arrow = new createjs.Shape();
        arrow.graphics.beginStroke(createjs.Graphics.getRGB(0, 0, 0)).moveTo(-5, +5).lineTo(0, 0).lineTo(-5, -5);
    
        var degree = radian / Math.PI * 180;
        arrow.x = x;
        arrow.y = y;
        arrow.rotation = degree;
    
        stage.addChild(arrow);
    }