setTimeout、setInterval或requestAnimationFrame的区别是什么?

20

针对移动设备使用canvas动画的HTML5游戏。

我遇到了一些性能问题,不同设备之间的速度差异很大。

requestAnimationFrame 根据设备速度加速游戏动画。
setInterval 令我震惊的是,在不同设备上存在延迟。
setTimeout 也会减慢在canvas上绘制的速度。

有没有移动HTML5游戏开发经验的人可以指导我哪种方法最好(或者其他可用技术)以实现在不同移动设备上稳定运行的canvas动画?

3个回答

21

尽可能使用requestAnimationFrame,因为这是它的本意。当不行时最好使用支持的shim,这样您就不需要处理具体细节。

为了使动画或游戏逻辑在使用的方法不同的情况下以相同的速度执行,您应该使用基于时间的动画和物理学或类似物理学的基于时间的计算。


安卓手机浏览器的旧版本不支持requestAnimationFrame(HTC)......我在HTC设备上尝试了这个网站http://ie.microsoft.com/testdrive/Graphics/RequestAnimationFrame/Default.html,但它不受支持!! - Soliman
1
@Solieman Paul Irish发布了一篇关于requestAnimationFrame的很棒的博客文章,其中还有一个shim:http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - Jasper
@Solieman 我链接的代码(shim)会处理使用正确的方法。如果不支持requestAnimationFrame,它将自动使用其他方法之一。Jasper的链接上有更多信息。 - Jani Hartikainen
+1。这个线程也很相关。http://stackoverflow.com/questions/14508085/requestanimationframe-running-slow-on-weak-machines-work-around - Ben

10
window.requestAnimFrame = function(){
    return (
        window.requestAnimationFrame       || 
        window.webkitRequestAnimationFrame || 
        window.mozRequestAnimationFrame    || 
        window.oRequestAnimationFrame      || 
        window.msRequestAnimationFrame     || 
        function(/* function */ draw1){
            window.setTimeout(draw1, 1000 / 60);
        }
    );
}();
   window.requestAnimFrame(draw);
})();

对于所有情况,请使用此函数。


1
1000 / 60 是什么意思?为什么不直接使用一个简单的 resultant / evaluated 数字呢?此外,这是从GitHub复制的解决方案,没有给原始发布者以功劳。 - user2836237
每秒60帧 - Kris Krause

0

优化 自requestAnimationFrame()引入以来一直很友好,如果当前窗口或选项卡不可见,则会导致动画停止。

https://flaviocopes.com/requestanimationframe/

 var count = 0;
    const IDS = requestAnimationFrame(repeatOften);

        function repeatOften() {
            count++;
            if(count > 4 ){
                // cancelAnimationFrame (IDS);
                 console.warn('finish');
                 return;
            }
            console.log('init' + count);
            // Do whatever
            requestAnimationFrame(repeatOften);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接