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

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


当前回答

我总是用这个

ctx.clearRect(0, 0, canvas.width, canvas.height)
window.requestAnimationFrame(functionToBeCalled)

NOTE

结合clearRect和requestAnimationFrame允许更流畅的动画,如果这是你想要的

其他回答

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

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

这些都是如何清除标准画布的好例子,但如果你使用的是paperjs,那么这将工作:

用JavaScript定义一个全局变量:

var clearCanvas = false;

从你的PaperScript定义:

function onFrame(event){
    if(clearCanvas && project.activeLayer.hasChildren()){
        project.activeLayer.removeChildren();
        clearCanvas = false;
    }
}

现在无论你在哪里设置clearCanvas为true,它都会从屏幕上清除所有的项目。

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

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

用途:上下文。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

最快的方式:

canvas = document.getElementById("canvas");
c = canvas.getContext("2d");

//... some drawing here

i = c.createImageData(canvas.width, canvas.height);
c.putImageData(i, 0, 0); // clear context by putting empty image data