如何清除画布以进行重绘
在尝试合成操作并在画布上绘制图像之后,我现在尝试删除图像并合成。我该怎么做?
我需要清除画布以重绘其他图像;这可能会持续一段时间,所以我不认为每次都绘制一个新的矩形是最有效的选择。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在尝试合成操作并在画布上绘制图像之后,我现在尝试删除图像并合成。我该怎么做?
我需要清除画布以重绘其他图像;这可能会持续一段时间,所以我不认为每次都绘制一个新的矩形是最有效的选择。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(26)
鉴于
canvas
是一个画布元素或 < code>OffscreenCanvas 对象,使用 <代码>clearRect:Given that
canvas
is a canvas element or anOffscreenCanvas
object, useclearRect
:使用:
context.clearRect(0, 0, canvas.width, canvas.height);
这是清除整个画布最快且最具描述性的方法。
不要使用:
canvas.width = canvas.width;
重置
canvas.width
会重置所有画布状态(例如变换、lineWidth、行程样式等),速度非常慢(与clearRect相比),它并不适用于所有浏览器,并且它没有描述您实际尝试执行的操作。处理变换后的坐标
如果您修改了变换矩阵(例如使用
scale
、rotate
或translate
),则context.clearRect( 0,0,canvas.width,canvas.height)
可能不会清除画布的整个可见部分。解决方案是什么?在清除画布之前重置变换矩阵:
编辑:
我刚刚做了一些分析,(在 Chrome 中)在不重置变换的情况下清除 300x150(默认大小)画布的速度大约快 10%。随着画布尺寸的增加,这种差异就会减小。
这已经相对微不足道了,但在大多数情况下,您绘制的内容将远远多于您清除的内容,我相信这种性能差异是无关紧要的。
Use:
context.clearRect(0, 0, canvas.width, canvas.height);
This is the fastest and most descriptive way to clear the entire canvas.
Do not use:
canvas.width = canvas.width;
Resetting
canvas.width
resets all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.), it is very slow (compared to clearRect), it doesn't work in all browsers, and it doesn't describe what you are actually trying to do.Dealing with transformed coordinates
If you have modified the transformation matrix (e.g. using
scale
,rotate
, ortranslate
) thencontext.clearRect(0,0,canvas.width,canvas.height)
will likely not clear the entire visible portion of the canvas.The solution? Reset the transformation matrix prior to clearing the canvas:
Edit:
I've just done some profiling and (in Chrome) it is about 10% faster to clear a 300x150 (default size) canvas without resetting the transform. As the size of your canvas increases this difference drops.
That is already relatively insignificant, but in most cases you will be drawing considerably more than you are clearing and I believe this performance difference be irrelevant.
如果您正在绘制线条,请确保不要忘记:
否则线条将不会被清除。
If you are drawing lines, make sure you don't forget:
Otherwise the lines won't get cleared.
其他人已经很好地回答了这个问题,但是如果上下文对象上的简单
clear()
方法对您有用(对我来说),那么这就是我根据答案使用的实现在这里:用法:
Others have already done an excellent job answering the question but if a simple
clear()
method on the context object would be useful to you (it was to me), this is the implementation I use based on answers here:Usage:
现在已经是 2018 年了,仍然没有本地方法可以完全清除画布以进行重绘。
clearRect()
不完全清除画布。非填充类型的绘图不会被清除(例如rect()
)1.无论您如何绘制,都要完全清除画布:
优点:保留描边样式、填充样式等。 ;无滞后;
缺点:如果您在绘制任何内容之前已经使用了 beginPath,则没有必要
2.使用宽度/高度 hack:
或
优点:适用于 IE
缺点:将描边样式、填充样式重置为黑色;拉吉;
我想知道为什么不存在本机解决方案。实际上,
clearRect()
被视为单行解决方案,因为大多数用户在绘制任何新路径之前都会执行beginPath()
操作。虽然 beginPath 只能在绘制线条时使用,而不是像 rect() 这样的闭合路径。这就是为什么接受的答案没有解决我的问题并且我最终浪费了时间尝试不同的黑客的原因。诅咒你莫兹拉
This is 2018 and still there is no native method to completely clear canvas for redrawing.
clearRect()
does not clear the canvas completely. Non-fill type drawings are not cleared out (eg.rect()
)1.To completely clear canvas irrespective of how you draw:
Pros: Preserves strokeStyle, fillStyle etc.; No lag;
Cons: Unnecessary if you are already using beginPath before drawing anything
2.Using the width/height hack:
OR
Pros: Works with IE
Cons: Resets strokeStyle, fillStyle to black; Laggy;
I was wondering why a native solution does not exist. Actually,
clearRect()
is considered as the single line solution because most users dobeginPath()
before drawing any new path. Though beginPath is only to be used while drawing lines and not closed path likerect().
This is the reason why the accepted answer did not solve my problem and I ended up wasting hours trying different hacks. Curse you mozilla
context.clearRect ( x , y , w , h );
正如 @Pentium10 所建议的,但 IE9 似乎完全忽略了这条指令。canvas.width = canvas.width;
但它不会清除线条,只会清除形状、图片和其他对象,除非您还使用 @John Allsopp 的首先更改宽度的解决方案。因此,如果您有这样创建的画布和上下文:
您可以使用如下方法:
context.clearRect ( x , y , w , h );
as suggested by @Pentium10 but IE9 seems to completely ignore this instruction.canvas.width = canvas.width;
but it doesn't clear lines, just shapes, pictures and other objects unless you also use @John Allsopp's solution of first changing the width.So if you have a canvas and context created like this:
You can use a method like this:
通过传递 x,y 坐标以及画布的高度和宽度来使用 clearRect 方法。 ClearRect 将清除整个画布:
Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :
一个快速的方法是不
知道它是如何工作的,但它确实如此!
A quick way is to do
Idk how it works but it does!
这里有很多好的答案。
还要注意的是,有时仅部分清除画布很有趣。
也就是说,“淡出”先前的图像而不是完全删除它。
这可以产生很好的轨迹效果。
这很容易。假设你的背景颜色是白色:
there are a ton of good answers here.
one further note is that sometimes it's fun to only partially clear the canvas.
that is, "fade out" the previous image instead of erasing it entirely.
this can give nice trails effects.
it's easy. supposing your background color is white:
这就是我使用的,无论边界和矩阵转换如何:
基本上,它保存上下文的当前状态,并使用
copy
作为globalCompositeOperation
。然后,恢复之前的上下文状态。This is what I use, regardless boundaries and matrix transformations:
Basically, it saves the current state of the context, and draws a transparent pixel with
copy
asglobalCompositeOperation
. Then, restores the previous context state.我总是使用
用于自定义颜色,以及
用于在清除时使画布透明
I always use
For a custom color, and
For making the canvas transparent when clearing
我发现在我测试的所有浏览器中,最快的方法实际上是用白色或任何您想要的颜色填充矩形。我有一个非常大的显示器,在全屏模式下,clearRect 非常慢,但 fillRect 是合理的。
缺点是画布不再透明。
I have found that in all browsers I test, the fastest way is to actually fillRect with white, or whataever color you would like. I have a very large monitor and in full screen mode the clearRect is agonizingly slow, but the fillRect is reasonable.
The drawback is that the canvas is no longer transparent.
这适用于 Chart.js 中的饼图
This worked for my pieChart in chart.js
最短路线:
the shortest way:
现在有一个
.reset()
方法不仅会清除画布缓冲区,还会完全重置上下文的所有属性(样式等),重置其转换矩阵,清除其当前子路径,清除其状态堆栈(由save()
和restore()
),并删除所有剪切区域。基本上,它与canvas.width += 0 具有相同的效果,只是它更惯用。
然而,在当前的 Chromium 实现中,它似乎与
canvas.width += 0
一样慢,它还会生成一个新的缓冲区,而不是简单地清除前一个缓冲区(导致更多的内存垃圾)。另一个需要注意的是,它目前仅在 Chromium 浏览器中受支持。不过要填充它,你可以采用 Chrome 方式
There is now a
.reset()
method which will not only clear the canvas buffer but also completely reset all the properties of the context (styles etc.), reset its transformation matrix, clear its current sub-path, clear its states stack (the one controlled bysave()
andrestore()
), and remove all the clipping regions.Basically, it has the same effects as
canvas.width += 0
, except that it's more idiomatic.However it seems that in current Chromium's implementation it's as slow as
canvas.width += 0
, it also does generate a new buffer instead of simply clearing the previous one (resulting in more memory garbage). Another caveat is that it's currently only supported in Chromium browsers.Though to polyfill it you can go the Chrome way
在webkit中你需要将宽度设置为不同的值,然后你可以将其设置回初始值
in webkit you need to set the width to a different value, then you can set it back to the initial value
一个简单但不太可读的方法是这样写:
A simple, but not very readable way is to write this:
示例:context.clearRect(0, 0, canvas.width, canvas.height);
Example:
context.clearRect(0, 0, canvas.width, canvas.height);
我总是使用这个
注意
结合clearRect和requestAnimationFrame允许更流畅的动画,如果这就是你想要的
I always use this
NOTE
combining clearRect and requestAnimationFrame allows for more fluid animation if that is what you're going for
如果您仅使用clearRect,如果您在表单中使用它来提交绘图,您将得到一个提交而不是清除,或者也许可以先清除它,然后上传一个无效绘图,所以您需要添加一个在函数开始时阻止默认:
希望它对某人有帮助。
If you use clearRect only, if you have it in a form to submit your drawing, you'll get a submit instead the clearing, or maybe it can be cleared first and then upload a void drawing, so you'll need to add a preventDefault at the beggining of the function:
Hope it helps someone.
这是一个带有透明画布按钮的自由手绘画布。
请参阅这个画布的实时示例,您可以在其上进行绘制,并且在需要时清除它以进行重绘
clearRect()
用于删除当前的画布,而fillRect( )
用于再次绘制初始画布,该画布是干净的并且上面没有任何绘图。This is a Free hand drawing Canvas with a Clear Canvas Button.
See this live example of a canvas which you can draw on and also when required clear it for redrawing
clearRect()
is used to delete the prersent canvas andfillRect()
is used to again draw the initial canvas which was clean and had no drawings on it.这些都是如何清除标准画布的好例子,但是如果您使用 paperjs,那么这将起作用:
在 JavaScript 中定义一个全局变量:
从您的 PaperScript 定义:
现在,无论您将clearCanvas 设置为 true,它都会清除所有屏幕上的项目。
These are all great examples of how you clear a standard canvas, but if you are using paperjs, then this will work:
Define a global variable in JavaScript:
From your PaperScript define:
Now wherever you set clearCanvas to true, it will clear all the items from the screen.
最快的方法:
fastest way:
如果你不使用转换,这会做到这一点:
我通常用背景颜色的矩形填充整个画布
如果应用转换 - 你可以
getTransform
并做一些学校数学来清除画布中的画布应用变换空间。它并不那么复杂,但是昨天我花了一些时间在纸上,当时我需要将鼠标位置转换到每个绘制元素的本地空间(用于碰撞检查):a,b,c,d,e,f - 是画布矩阵数据,X,Y - 鼠标位置,x,y - 本地空间中的位置
您需要对所有 4 个角 (0,0),(w,0),(w,h),(0 ,h),然后获取所有结果 x 和 y 的最小值/最大值,然后使用
fillRect
或clearRect
获取带有参数的 rect:(minX, minY, maxX-minX, maxY -minY)我认为这在性能方面并不是最佳的。实际上,我认为最高效的方法是获取空画布的 getImageData 并通过 putImageData 方法将其放回原处,但性能测试表明情况并非如此。清除是否应用转换的最佳方法是:
Here is a jsperf link 其中包含我尝试过的所有选项。
If you do not use transformations this would do the thing:
I usually fill the full canvas with a rect of background color
If transformations are applied — you can
getTransform
and do some school math to clear the canvas in the applied transform space. It is not so complicated, but I spent some time yesterday with paper when I needed to transform the mouse position to the local space of each drawn element (for collision check):a, b, c, d, e, f — is the canvas matrix data, X, Y — mouse position, and x, y — position in local space
You would need to do it for all 4 corners (0,0), (w,0), (w,h), (0,h), then get min/max of all results x, and y, then
fillRect
orclearRect
for rect with arguments: (minX, minY, maxX-minX, maxY-minY)I do not think it would be optimal in the performance term way. Actually, I thought that the most performant way would be to
getImageData
of an empty canvas and put it back by theputImageData
method, but performance tests show that this is not the case. An optimal way to clear if transformations are applied is:Here is a jsperf link with all options that I've tried.