clearRect function doesn't clear the canvas

2020-01-23 04:08发布

I'm using this script on the body onmousemove function:

function lineDraw() {
    // Get the context and the canvas:
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    // Clear the last canvas
    context.clearRect(0, 0, canvas.width, canvas.height);
    // Draw the line:
    context.moveTo(0, 0);
    context.lineTo(event.clientX, event.clientY);
    context.stroke();
}

It's supposed to clear the canvas each time I move the mouse around, and draw a new line, but it isn't working properly. I'm trying to solve it without using jQuery, mouse listeners or similar.

Here is a demo: https://jsfiddle.net/0y4wf31k/

3条回答
狗以群分
2楼-- · 2020-01-23 04:22

You should use "beginPath()". That is it.

function lineDraw() {   
    var canvas=document.getElementById("myCanvas");
    var context=canvas.getContext("2d");
    context.clearRect(0, 0, context.width,context.height);
    context.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<
    context.moveTo(0,0);
    context.lineTo(event.clientX,event.clientY);
    context.stroke();
}
查看更多
我命由我不由天
3楼-- · 2020-01-23 04:30

Be advised that ctx.clearRect() does not work properly on Google Chrome. I spent hours trying to solve a related problem, only to find that on Chrome, instead of filling the rectangle with rgba(0, 0, 0, 0), it actually fills the rectangle with rgba(0, 0, 0, 1) instead!

Consequently, in order to have the rectangle filled properly with the required transparent black pixels, you need, on Chrome, to do this instead:

ctx.fillStyle = "rgba(0, 0, 0, 0)";
ctx.fillRect(left, top, width, height);

This should, of course, work on all browsers providing proper support for the HTML5 Canvas object.

查看更多
三岁会撩人
4楼-- · 2020-01-23 04:42

Try with context.canvas.width = context.canvas.width:

function lineDraw() {   
    var canvas=document.getElementById("myCanvas");
    var context=canvas.getContext("2d");
    //context.clearRect(0, 0, context.width,context.height);
    context.canvas.width = context.canvas.width;
    context.moveTo(0,0);
    context.lineTo(event.clientX,event.clientY);
    context.stroke();
}

Demo HERE

查看更多
登录 后发表回答