使用requestAnimationFrame实现一些稳定的帧速率?

acr*_*uui 9 javascript performance animation requestanimationframe

我正在玩这个requestAnimationFrame但是我在除了Chrome之外的任何其他浏览器中都有非常生涩的动画.

我创建一个像这样的对象:

var object = function() {

    var lastrender = (new Date()).getTime();
    var delta = 0;

    return {

        update: function() {
             //do updates using delta value in calculations.
        },

        loop: function() {
            var looptimestamp = (new Date()).getTime();
            delta = looptimestamp - lastrender;
            lastrender = looptimestamp;

            this.update();

            window.requestAnimationFrame(this.loop.bind(this));
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

现在我只是在画布元素上绘制一个矩形并移动它.它是处理器上非常轻量级的操作.这在Chrome中运行得相当顺利,当我控制日志记录delta值时,它几乎在~17左右.但是,如果我在Firefox或Safari中执行相同操作,则会获得以下delta值:

17-3-17-2-32-34-32-31-19-31-17-3-0-14-3-14-35-31-16-3-17-2 ... and so on
Run Code Online (Sandbox Code Playgroud)

看起来好像浏览器没有很好地与显示器同步,并且在除Chrome之外的所有其他情况下,使用旧的setTimeout方法以16ms作为目标超时,可以获得更平滑的动画.

有谁知道,如果可以requestAnimationFrame在Chrome以外的浏览器中使用更流畅的动画?有没有人成功获得比上面在Firefox中发布的更稳定的delta值?

fro*_*rli 0

如果在 delta < 阈值时跳过更新,您可能会获得更平滑的动画,例如:

if (delta > 5) this.update();
Run Code Online (Sandbox Code Playgroud)