Javascript clearRect 函数不会清除画布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13435959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
clearRect function doesn't clear the canvas
提问by Juan C. Roldán
I'm using this script on the body onmousemovefunction:
我在 bodyonmousemove函数上使用这个脚本:
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.
每次我移动鼠标时都应该清除画布并绘制一条新线,但它无法正常工作。我试图在不使用 jQuery、鼠标侦听器或类似的情况下解决它。
Here is a demo: https://jsfiddle.net/0y4wf31k/
这是一个演示:https: //jsfiddle.net/0y4wf31k/
回答by aviomaksim
You should use "beginPath()". That is it.
您应该使用“ 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();
}
回答by David Edwards
Be advised that ctx.clearRect() does notwork 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 actuallyfills the rectangle with rgba(0, 0, 0, 1) instead!
请注意 ctx.clearRect()在 Google Chrome 上无法正常工作。我花了几个小时试图解决相关的问题,才发现在Chrome,而不是填充RGBA(0,0,0,0)的矩形,它实际上填满了RGBA(0,0,0,1)矩形反而!
Consequently, in order to have the rectangle filled properlywith the required transparent black pixels, you need, on Chrome, to do this instead:
因此,为了使用所需的透明黑色像素正确填充矩形,您需要在 Chrome 上执行以下操作:
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.
当然,这应该适用于为 HTML5 Canvas 对象提供适当支持的所有浏览器。
回答by salih0vicX
Try with context.canvas.width = context.canvas.width:
尝试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
演示在这里

