setTimeout or setInterval or requestAnimationFrame



对于HTML5游戏,带有适用于移动设备的画布动画。

我遇到了一些性能问题,这些问题使每个设备与其他设备之间的速度不同。

请求动画帧速度

根据设备速度对游戏的动画进行帧速度。
setInterval让我震惊的是,从一个设备到另一个设备有延迟。
setTimeout 也会减慢画布上的绘图速度。

谁以前有过移动HTML5游戏的经验,可以指导我抛出其中三种(或其他技术,如果有的话)的最佳方法,用于在画布上开发动画在不同的移动设备上稳定?

尽可能始终使用requestAnimationFrame,因为这就是它的意思。最好在不需要时使用填充程序作为支持,这样您就不需要处理具体细节。

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

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);
})();

对所有情况都使用此函数

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

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);
        }

最新更新