Drawing to canvas like in paint

前端 未结 3 1586
小蘑菇
小蘑菇 2021-01-27 02:41

I have three arrys:

 clickX = [],
    clickY = [],
    clickDrag = [];

this is what happens when you click down:

$(\'#canvasCur         


        
3条回答
  •  猫巷女王i
    2021-01-27 03:20

    EDIT: Sorry, fixed some typos Edit 2: And again. It's a bit difficult to test.

    There's no reason to redraw each of the points each time. You could modify your listener to do this:

    var prevMouseX=null,prevMouseY=null;
    $('#canvasCursor').mousedown(function (e) {
        paint = true;
    
        console.log('down');
        //get current mouse coords
        mouseX = e.pageX - this.offsetLeft;
        mouseY = e.pageY - this.offsetTop;
    
        if (prevMouseX==null) {
            //store these coordinates for next time if they haven't been defined yet
            prevMouseX = mouseX;
            prevMouseY = mouseY;
        }
    });
    
    $('#canvasCursor').mousemove(function (e) {
        //get current mouse coords
        mouseX = e.pageX - this.offsetLeft;
        mouseY = e.pageY - this.offsetTop;
    
        if (prevMouseX==null) {
            //store these coordinates for next time if they haven't been defined yet
            prevMouseX = mouseX;
            prevMouseY = mouseY;
        }
    
        if (paint) {drawline(mouseX,mouseY,prevMouseX,prevMouseY);}
    
        //store these coordinates for next time
        prevMouseX = mouseX;
        prevMouseY = mouseY;
    });
    

    Where the function drawLine is defined as:

    function drawline(x1,y1,x2,y2) {
    ctx.strokeStyle = "green";
        ctx.lineJoin = "round";
        ctx.lineWidth = brushSize*2;
    
        ctx.beginPath();
        ctx.moveTo(x1,y1);
        ctx.lineTo(x2,y2);
        ctx.closePath();
        ctx.stroke();
    }
    

提交回复
热议问题