问题描述
此问题与,但我想确定我有正确的答案,我开始对我的代码进行重大更改。
我正在开发一个计算量很大的JavaScript程序,需要不断地更新HTML5画布中的图像来绘制动画。如现在写的,代码在紧凑的循环中绘制动画的所有帧,而不向浏览器返回控制,这意味着最终显示的只是最后一帧。我很确定唯一的方法来解决这个问题是将动画代码拆分为更小的部分,可以通过超时事件可重入地调用。它是否正确?或者是否有一种方法可以迫使画布在某个点显示其内容,即使在紧挨的JavaScript循环中也是如此?
blockquote>
我确定唯一的方法来解决这个问题是将动画代码分割成更小的片段,可以通过超时事件可重入地调用。它是否正确?
此是正确。
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?
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.
这篇关于强制HTML5画布在重JavaScript处理时重绘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!