在尝试了合成操作和在画布上绘制图像后,我现在试图删除图像和合成。我怎么做呢?

我需要清除画布重绘其他图像;这可能会持续一段时间,所以我不认为每次都画一个新的矩形是最有效的选择。


当前回答

在webkit中,您需要将宽度设置为不同的值,然后您可以将其设置回初始值

其他回答

一种简单但不太好读的方式是这样写的:

var canvas = document.getElementId('canvas');

// after doing some rendering

canvas.width = canvas.width;  // clear the whole canvas

如果你在画线条,请确保不要忘记:

context.beginPath();

否则这些行就不会被清除。

最短的方法:

canvas.width += 0

Chrome响应良好:上下文。clearRect (x, y, w, h);正如@Pentium10所建议的,但IE9似乎完全忽略了这条指令。 IE9似乎对:canvas做出了响应。宽度= canvas.width;但它不清除线条,只是形状,图片和其他物体,除非你也使用@John Allsopp的解决方案,首先改变宽度。

如果你有一个canvas和context是这样创建的:

var canvas = document.getElementById('my-canvas');
var context = canvas.getContext('2d');

你可以使用这样的方法:

function clearCanvas(context, canvas) {
  context.clearRect(0, 0, canvas.width, canvas.height);
  var w = canvas.width;
  canvas.width = 1;
  canvas.width = w;
}

我总是用

ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillRect(0, 0, canvas.width, canvas.height);

对于自定义颜色,和

ctx.clearRect(0, 0, canvas.width, canvas.height);

用于使画布透明时清除