使用Web Workers使用本机canvas函数进行绘制 [英] Using Web Workers for drawing using native canvas functions

查看:190
本文介绍了使用Web Workers使用本机canvas函数进行绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过 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.

我找到了关于MDN的通知


注意:像往常一样,后台线程 - 包括工人 - 不能操纵DOM。如果后台线程采取的操作需要导致DOM的更改,他们应该将消息发回给他们的创建者来完成这项工作。

Note: As usual, background threads—including workers—cannot manipulate the DOM. If actions taken by the background thread need to result in changes to the DOM, they should post messages back to their creators to do that work.



<但是我想把DOM保留原样;我只是想在canvas元素上绘制东西。这是可能的,还是Web Workers真的只允许计算而不是绘制?

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函数进行绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆