在进行繁重的 JavaScript 处理时强制 HTML5 画布重绘?

发布于 2024-11-07 23:01:55 字数 402 浏览 0 评论 0原文

这个问题与 这个旧的,,但我想在开始对代码进行重大更改之前确保我有正确的答案。

我正在开发一个计算密集型的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生活了然无味 2024-11-14 23:01:55

我很确定解决此问题的唯一方法是将动画代码分割成更小的片段,这些片段可以通过超时事件重入调用。这是正确的吗?

正确的。

Javascript 是单线程的,因此在执行逻辑时无法发生任何其他事情。您唯一的选择是通过将逻辑拆分为要在超时时执行的微块来“模拟”线程。

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?

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.

So要识趣 2024-11-14 23:01:55

如果可用,您可以使用网络工作者来实现此目的。只需计算您需要在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文