使用 Web Workers 使用本机画布函数进行绘图

Using Web Workers for drawing using native canvas functions(使用 Web Workers 使用本机画布函数进行绘图)

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

问题描述

可以将通过 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 上找到了 这个通知:

I did find this notice on 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 原样;我只是想在画布元素上画东西.这可能吗,还是 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 使用本机画布函数进行绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 Web Workers 使用本机画布函数进行绘图

基础教程推荐