clearRect函数不会清除画布

Jua*_*dán 29 javascript line onmousemove draw clear

我在body onmousemove函数上使用这个脚本:

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();
}
Run Code Online (Sandbox Code Playgroud)

每次我移动鼠标时都应该清除画布,然后绘制一条新线,但它不能正常工作.我试图在不使用jQuery,鼠标监听器或类似工具的情况下解决它.

这是一个演示:https://jsfiddle.net/0y4wf31k/

avi*_*sim 63

你应该使用" beginPath() ".这就对了.

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 想补充一点,这也适用于 rect 和 arc 等绘制方法。 (3认同)
  • 谢谢你!这太疯狂了,为什么除非你执行“beginPath”,否则清除会失败?这个不成立。 (3认同)
  • 它已经过时了但是......"closePath"在这里是无用的和误导的,它只是一个`lineTo(previousStartingPointOfThePath)`所以对于一行,它不会做任何事情,它根本不能说明你完成了你的路径宣言. (2认同)

Dav*_*rds 8

请注意,ctx.clearRect()在 Google Chrome 上无法正常工作我花了几个小时试图解决一个相关问题,结果发现在 Chrome 上,它不是用 rgba(0, 0, 0, 0) 填充矩形,而是用rgba (0, 0, 0, 1) 填充矩形反而!

因此,为了用所需的透明黑色像素正确填充矩形,您需要在 Chrome 上执行以下操作:

ctx.fillStyle = "rgba(0, 0, 0, 0)";
ctx.fillRect(left, top, width, height);
Run Code Online (Sandbox Code Playgroud)

当然,这应该适用于为 HTML5 Canvas 对象提供适当支持的所有浏览器。