使用Jquery在画布上单击两次鼠标绘制一条线

时间:2012-07-09 22:41:04

标签: jquery html5 canvas click draw

我已经看过这个问题了

  

Draw a line with two mouse clicks on HTML5 canvas?

我想要实现的几乎相同,但使用Jquery。

我目前已尝试this,但我想我无法使用两个嵌套点击事件。

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

     })

  })


 })​

当我在lineTo()中放置一些静态值时,我得到this,它识别第二个点的坐标,从而绘制线,即使用户不这样做也没用自己设定第二点。

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

    })

 })


})​

1 个答案:

答案 0 :(得分:4)

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