如何强制画布中的显示更新
如果我快速连续地在画布上绘制很多内容,例如循环中的 context.fillRect ,浏览器似乎会等到循环完成后再显示任何绘图(可能通过双缓冲)
有没有办法强制浏览器在每次绘制操作后显式或隐式更新显示?
if I draw to the canvas a lot in quick succession, e.g. a context.fillRect in a loop, browsers seem to wait until the loop has finished before any of the drawing is displayed (possibly via double-buffering)
Is there any way to force the browser to update the display, either explicitly or implicitly after each draw operation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不是因为双缓冲而看不到结果,而是因为 Web 浏览器中的 JavaScript 是单线程的。如果您在 JavaScript 中类似地创建一个循环,重复执行类似
myDiv.style.top = parseInt(myDiv.style.top) + 1 +"px";
的操作,您会发现没有任何明显变化在浏览器中 - 甚至需要很多秒 - 直到你的 JavaScript 完成执行。要绘制更改并在屏幕上查看结果,您需要使用
setInterval
或setTimeout
将控制权交还给浏览器,但要求在将来的某个时刻运行代码。例如,每秒在画布上绘制一个新的随机、随机颜色的矩形 15 次:
It is not really because of any double-buffering that you don't see the results, but rather because JavaScript in the web browser is single-threaded. If you similarly create a single loop in JavaScript that repeatedly does something like
myDiv.style.top = parseInt(myDiv.style.top) + 1 +"px";
you will see that nothing will visibly change in the browser—even over many seconds—until your JavaScript has finished executing.To draw changes and see the results on the screen, you need to use
setInterval
orsetTimeout
to yield control back to the browser but ask to run code at some point in the future.For example, to draw a new random, randomly-colored rectangle on the canvas 15 times a second:
最好使用
window.requestAnimationFrame()< /code>
以获得更好的浏览器行为。
It is better to use
window.requestAnimationFrame()
for better browser behaviour.