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

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


当前回答

其他人已经很好地回答了这个问题,但如果一个简单的context对象上的clear()方法对你(对我)有用,这是我基于这里的答案使用的实现:

CanvasRenderingContext2D.prototype.clear = 
  CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {
    if (preserveTransform) {
      this.save();
      this.setTransform(1, 0, 0, 1, 0, 0);
    }

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

    if (preserveTransform) {
      this.restore();
    }           
};

用法:

window.onload = function () {
  var canvas = document.getElementById('canvasId');
  var context = canvas.getContext('2d');

  // do some drawing
  context.clear();

  // do some more drawing
  context.setTransform(-1, 0, 0, 1, 200, 200);
  // do some drawing with the new transform
  context.clear(true);
  // draw more, still using the preserved transform
};

其他回答

用途:上下文。clearRect(0,0, canvas.)宽度,canvas.height);

这是清除整个画布的最快和最直观的方法。

不要使用:canvas。宽度= canvas.width;

重置画布。width重置所有的画布状态(例如,转换,lineWidth, strokeStyle等),它非常慢(与clearRect相比),它不能在所有浏览器中工作,并且它不能描述你实际上试图做什么。

处理变换后的坐标

如果你已经修改了转换矩阵(例如使用缩放,旋转或翻译),那么context.clearRect(0,0,canvas.width,canvas.height)可能不会清除画布的整个可见部分。

解决方案?在清除画布之前重置转换矩阵:

// Store the current transformation matrix
context.save();

// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);

// Restore the transform
context.restore();

编辑: 我刚刚做了一些分析(在Chrome中),它是大约10%的速度,以清除一个300x150(默认大小)的画布,而不重置转换。随着画布尺寸的增加,这种差异就会减小。

这已经是相对微不足道的了,但在大多数情况下,您提取的金额将远远超过您出清的金额,我相信这种性能差异是无关紧要的。

100000 iterations averaged 10 times:
1885ms to clear
2112ms to reset and clear

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

context.beginPath();

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

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

使用clearRect方法通过传递x,y坐标和画布的高度和宽度。ClearRect将清除整个画布:

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

我发现在我测试的所有浏览器中,最快的方法是用白色填充rect,或者任何你想要的颜色。我有一个非常大的显示器,在全屏模式下,clearRect非常慢,但fillRect是合理的。

context.fillStyle = "#ffffff";
context.fillRect(0,0,canvas.width, canvas.height);

缺点是画布不再是透明的。