[英]Proper way to perform update/draw loops on a canvas with requestAnimationFrame
[英]Is this the proper way to use requestAnimationFrame?
我有一个我编写的软件,它会在更新逻辑完成后立即触发屏幕重绘。 问题是更新逻辑每秒发生超过 1000 次。 浏览器无法如此快速地更新屏幕,因此我认为 requestAnimationFrame 将允许我以较慢的方式为用户更新屏幕。
我这样构造代码:
function repaint(){
now = Date.now();
elapsed = now-then;
if(elapsed > 2000){
.
.
.
//animation goes here
.
.
.
then = Date.now();
}
}
function startRepaint(){
then = Date.now();
requestAnimationFrame(repaint);
}
while(count < 1000){
.
.
.
startRepaint();
.
.
.
}
我可以以这种方式使用 requestAnimationFrame 来实现我想要的功能吗?
你在这里拥有的不是你想要的。
每次执行 while 循环时,都会调用startRepaint()
,它会发出对动画帧的请求。
第一次调用该函数后,您将遍历 while 循环并再次调用它。 当您第二次调用此函数时,您可能还没有收到第一个动画帧。
理想情况下,您希望对其进行设置,以便调用更新函数,该函数又会发送下一个请求。
function repaint() {
...
requestAnimationFrame(repaint);
}
这样做可以确保您在尝试开始下一个之前始终完成完整的代码框架。
您可以在重绘函数中使用计数器变量来跟踪迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.