hncl
hncl

Reputation: 2295

Kinetic JS - drawing arrowhead at start and end of a line using mouse

I am trying to add arrowhead to the start and end of lines that I am drawing using the mouse, here is my script for drawing the line:

    document.getElementById('dLine').onclick = function() {
    layer.on("mousedown", function () {
        if (moving) {
            moving = false;
            layer.draw();
        } else {
            var mousePos = stage.getMousePosition();
            x1 = mousePos.x;
            y1 = mousePos.y;
            line = new Kinetic.Line({
                points: [0, 0, 50, 50],
                stroke: "red"
            });
            layer.add(line);
            line.getPoints()[0].x = mousePos.x;
            line.getPoints()[0].y = mousePos.y;
            line.getPoints()[1].x = mousePos.x;
            line.getPoints()[1].y = mousePos.y;
            moving = true;
            layer.drawScene();
        }
    });

    layer.on("mousemove", function () {
        if (moving) {
            var mousePos = stage.getMousePosition();
            var x = mousePos.x;
            var y = mousePos.y;
            line.getPoints()[1].x = mousePos.x;
            line.getPoints()[1].y = mousePos.y;
            moving = true;
            layer.drawScene();
        }
    });

    layer.on("mouseup", function () {
        moving = false;
        var mousePos = stage.getMousePosition();
        x2 = mousePos.x;
        y2 = mousePos.y;
        $("#distance").val(calculateDistance(x1, y1, x2, y2));

    });
};

I would appreciate your suggestions.

Upvotes: 2

Views: 2919

Answers (1)

SoluableNonagon
SoluableNonagon

Reputation: 11755

You can use this function to draw an arrow:

function canvas_arrow(fromx, fromy, tox, toy){
    var headlen = 20;   // how long you want the head of the arrow to be, you could calculate this as a fraction of the distance between the points as well.
    var angle = Math.atan2(toy-fromy,tox-fromx);

    line = new Kinetic.Line({
        points: [fromx, fromy, tox, toy, tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6),tox, toy, tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6)],
        stroke: "red"
    });
}

Edit: jsfiddle.net/cmcculloh/M56w4 - provided in the comments

Upvotes: 5

Related Questions