在尝试了合成操作和在画布上绘制图像后,我现在试图删除图像和合成。我怎么做呢?
我需要清除画布重绘其他图像;这可能会持续一段时间,所以我不认为每次都画一个新的矩形是最有效的选择。
在尝试了合成操作和在画布上绘制图像后,我现在试图删除图像和合成。我怎么做呢?
我需要清除画布重绘其他图像;这可能会持续一段时间,所以我不认为每次都画一个新的矩形是最有效的选择。
当前回答
用途:上下文。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.width += 0
使用clearRect方法通过传递x,y坐标和画布的高度和宽度。ClearRect将清除整个画布:
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
这是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
这是我使用的,不管边界和矩阵变换:
function clearCanvas(canvas) {
const ctx = canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'copy';
ctx.strokeStyle = 'transparent';
ctx.beginPath();
ctx.lineTo(0, 0);
ctx.stroke();
ctx.restore();
}
基本上,它保存了上下文的当前状态,并以globalCompositeOperation为copy绘制了一个透明像素。然后,恢复以前的上下文状态。
一种简单但不太好读的方式是这样写的:
var canvas = document.getElementId('canvas');
// after doing some rendering
canvas.width = canvas.width; // clear the whole canvas