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

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


当前回答

假设canvas是一个canvas元素或者OffscreenCanvas对象,使用clearRect:

const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);

其他回答

假设canvas是一个canvas元素或者OffscreenCanvas对象,使用clearRect:

const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);

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

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

context.beginPath();

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

这是2018年,仍然没有本地的方法来完全清除画布重新绘制。clearRect()不会完全清除画布。非填充型图纸不清除(例如。矩形())

1.要完全清除画布,无论你如何绘制:

context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.beginPath();

优点:保留strokeStyle, fillStyle等;没有滞后;

缺点:如果你在绘制任何东西之前已经使用了beginPath,那就不必要了

2.使用宽度/高度hack:

context.canvas.width = context.canvas.width;

OR

context.canvas.height = context.canvas.height;

优点:与IE兼容 缺点:重置strokeStyle, fillStyle为黑色;延迟;

我想知道为什么本地解决方案不存在。实际上,clearRect()被认为是单行解决方案,因为大多数用户在绘制任何新路径之前都会执行beginPath()。虽然beginPath只在绘制线条时使用,而不是像rect()那样使用封闭路径。

这就是为什么接受的答案并没有解决我的问题,我最终浪费时间尝试不同的方法。诅咒你mozilla

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;
}