如何使用CreateJS绘制弯曲箭头?

时间:2014-09-09 01:24:03

标签: javascript canvas createjs

用于绘制弯曲箭头的JavaScript代码已经在这个小提琴中可用:http://jsfiddle.net/SguzM/

我想使用CreateJS库做同样的事情。

上面提到的代码如下:

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

1 个答案:

答案 0 :(得分:2)

在CreateJS中,Graphics class提供了用于绘制曲线的arc / arcTo,bezierCurveTo和quadraticCurveTo方法。

您可以使用Math.atan2(y, x).在CreateJS rotation属性中使用度数轻松计算斜率的弧度值,因此将弧度值转换为度数并按度数值旋转箭头。

这是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);
}