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

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


当前回答

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

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

其他回答

Context.clearRect(starting width, starting height, ending width, ending height);

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

其他人已经很好地回答了这个问题,但如果一个简单的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
};

这是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

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

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

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

我总是用

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

对于自定义颜色,和

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

用于使画布透明时清除