Erik
Erik

Reputation: 335

Drawing straight lines between mouse clicks using Canvas and jQuery

I want to draw a line in Canvas with jQuery and to define starting position with mouse click. On every additional mouse click I want to continue my line from the previous position.

I wrote some code, but the problem is that my line doesn't start from the mouseClick position; it starts from the default (0, 0). What do I have to change so that my line will be start from the mouse click position?

Thanks.

Here is my code:

var click = [0, 0];

contex.beginPath();
contex.moveTo(click[0], click[1]);
contex.lineTo(x, y);
contex.stroke();
click = [x, y];

Upvotes: 2

Views: 7035

Answers (1)

Matt Coughlin
Matt Coughlin

Reputation: 18906

Drawing a series of straight lines by clicking on the canvas:

JSFiddle demo

HTML

<canvas id="myCanvas" width="600" height="600"></canvas>

jQuery

var needFirstPoint = true;

function drawNextLine(ctx, x, y) {
    if (needFirstPoint) {
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(x, y);
        needFirstPoint = false;
    }
    else {
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}

$(document).ready(function(){
    var canvas = $('#myCanvas').get(0);
    if (!canvas.getContext) { return; }
    var ctx = canvas.getContext('2d');

    $('#myCanvas').on('click', function(e){
        var offset = $(this).offset();
        var x = e.pageX - offset.left;
        var y = e.pageY - offset.top;
        drawNextLine(ctx, x, y);
    });
});

Upvotes: 2

Related Questions