在进行繁重的 JavaScript 处理时强制 HTML5 画布重绘?
这个问题与 这个旧的,,但我想在开始对代码进行重大更改之前确保我有正确的答案。
我正在开发一个计算密集型的 JavaScript 程序,该程序需要不断更新 HTML5 画布中的图像来绘制动画。正如现在所写,代码在紧密循环中绘制动画的所有帧,而不将控制权返回给浏览器,这意味着最终显示的只是最终帧。我很确定解决此问题的唯一方法是将动画代码分割成更小的片段,这些片段可以通过超时事件重入调用。这是正确的吗?或者有没有办法强制画布在某个时刻显示其内容,即使是在紧密的 JavaScript 循环中?
This question is related to this older one, but I wanted to be sure I had the right answer before I started making major changes to my code.
I'm working on a very computation-intensive JavaScript program that needs to constantly update an image in an HTML5 canvas to draw an animation. As written now, the code draws all the frames of the animation in a tight loop without returning control to the browser, meaning that what's ultimately displayed is just the final frame. I'm pretty sure the only way to fix this is to split the animation code into smaller pieces that can be called reentrantly through a timeout event. Is this correct? Or is there a way to force the canvas to display its contents at a certain point even in the middle of a tight JavaScript loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是正确的。
Javascript 是单线程的,因此在执行逻辑时无法发生任何其他事情。您唯一的选择是通过将逻辑拆分为要在超时时执行的微块来“模拟”线程。
This is correct.
Javascript is single threaded, so there's no way for anything else to happen while your logic is being executed. Your only choice is to "emulate" threading by splitting your logic up in to micro-chunks to be executed on timeouts.
如果可用,您可以使用网络工作者来实现此目的。只需计算您需要在 webworkers 中执行的所有操作,并在完成后将结果发回即可。当您发回消息时,只需刷新图像即可。
计算将在后台完成,并且您的页面仅在更新图像时阻塞。
You could use webworkers for this if they are available. Just calculate everything you need to do in the webworkers and post the result back when it's done. When you post the message back you can just refresh the image.
Calculations will be done in the background and your page only blocks while updating the image.