menislici
menislici

Reputation: 1167

Draw a line with two mouse clicks in canvas using Jquery

I have already seen this question

Draw a line with two mouse clicks on HTML5 canvas?

What I want to achieve is practically the same, but using Jquery.

I have currently tried this, but I guess I can't use two nested click events.

 $(function() {

 var worksheetCanvas = $('#worksheet-canvas');

 var context = worksheetCanvas.get(0).getContext("2d");


context.strokeStyle = "rgb(251, 243, 243)";


 worksheetCanvas.click(function(e) {

    context.beginPath();


    var xCoordFirst = e.pageX;
    var yCoordFirst = e.pageY;

    context.moveTo(xCoordFirst, yCoordFirst);


    worksheetCanvas.click(function(f) {

        var xCoordSecond = f.pageX;
        var yCoordSecond = f.pageY;

        context.lineTo(xCoordSecond , yCoordSecond );
        context.closePath();
        context.stroke();

     })

  })


 })​

Also when I put some static values in lineTo(), I get this, which recognizes the coordinates for the second point, thus drawing the line, even though it is useless if the user doesn't set by themselves the second point.

 $(function() {

 var worksheetCanvas = $('#worksheet-canvas');

 var context = worksheetCanvas.get(0).getContext("2d");


context.strokeStyle = "rgb(251, 243, 243)";


worksheetCanvas.click(function(e) {

    context.beginPath();


    var xCoordFirst = e.pageX;
    var yCoordFirst = e.pageY;

    context.moveTo(xCoordFirst, yCoordFirst);


    worksheetCanvas.click(function(f) {

        var xCoordSecond = f.pageX;
        var yCoordSecond = f.pageY;

        context.lineTo(20 , 30);
        context.closePath();
        context.stroke();

    })

 })


})​

Upvotes: 1

Views: 3371

Answers (1)

Chief120
Chief120

Reputation: 305

var mouse = {
    x: -1,
    y: -1
};

$(document).ready(function(){
    var cvs = $("canvas")[0].getContext("2d");
    $("canvas").click(function(e){
        if(mouse.x != -1 && mouse.y != -1){
            cvs.beginPath();
            cvs.moveTo(mouse.x, mouse.y);
            cvs.lineTo(e.pageX, e.pageY);
            cvs.closePath();
            cvs.stroke();
            mouse.x = -1;
            mouse.y = -1;
        }else{
            mouse.x = e.pageX;
            mouse.y = e.pageY;
        }
    });
});

Upvotes: 5

Related Questions