问题描述
可以通过 getImageData
将 CanvasPixelArray
发送到工作脚本,然后让工作者脚本操作后台线程中的像素,最后将操纵的像素数组发回。
It's possible to send a CanvasPixelArray
obtained via getImageData
to a worker script, and let the worker script manipulate the pixels in its background thread, and eventually post the manipulated pixel array back.
然而,我使用的是原生画布绘图函数,如 drawImage
。 drawImage
调用当前正在阻止UI线程。这会导致按钮重绘速度慢,单击按钮时会出现明显的延迟,这只是为了说明一些缺点。 (编辑:现在可以使用 ctx.imageSmoothingEnabled = false
完成一项小改进,至少在使用 webkit
的WebKit上完成前缀。)
However, I'm using native canvas drawing functions, like drawImage
. The drawImage
calls are currently blocking the UI thread. This causes slow redraw of buttons, and a noticeable delay when clicking on a button, just to name a few drawbacks. ( A small improvement can now be accomplished with ctx.imageSmoothingEnabled = false
, at least on WebKit with the webkit
prefix.)
我想使用Web Workers将绘图从主线程移动到后台线程中。但是,我似乎无法将画布和上下文发送给工作人员。
I'd like to move the drawing from the main thread into a background thread using Web Workers. However, I don't seem to be able to send the canvas nor the context to the worker.
我找到了:
But I would like to leave the DOM as-is; I simply want to draw things on a canvas element. Is this possible, or are Web Workers really only allowed to calculate and not to draw?
(或者可能使用像 drawImage这样的函数
操纵 CanvasPixelArray
而不是在画布上绘图?)
(Or is it perhaps possible to use functions like drawImage
to manipulate a CanvasPixelArray
instead of drawing on a canvas?)
推荐答案
[社区编辑:这个答案是在2011年编写和接受的。其他技术已经出现(或正在出现),可以让Web Workers和Canvas更好地共存;除了这个答案之外,读者应该知道这个页面上的所有答案。]
你不能将画布对象或画布上下文传递给工作线程,因为画布是DOM的一部分。
You cannot pass a canvas object or canvas context to a worker thread because the canvas is part of the DOM.
这篇关于使用Web Workers使用本机canvas函数进行绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!