How do I make a JavaScript animation play at the same speed on all browsers on all systems?

天涯浪子 提交于 2019-11-30 20:33:49

The question is: How can I make sure the animation has a constant frame rate, and will run at the same speed on all browsers, on all systems?

You can't do anything about the framerate. The only thing you can control is how your application updates based on time passed. This is true outside of browsers as well, and a common topic in game development.

The best thing to do is track the delta (read: time difference) between updates.

(function () {
    function getTime() {
        return new Date().getTime();
    }
    var last = getTime();

    function update(delta) {
        // Update your application state on delta (ms of time passed)
    }

    (function loop() {
        update(last = getTime()-last);
        render();
        setTimeout(loop, 20); // 20 = attempt 50fps
    }());
}());

Notice the use of setTimeout here. This is to avoid the loop() from being called out of sync. setInterval will keep firing it even if a previous call didn't finish.

The answer is here, a great article by Glenn Fiedler, needs a little tweaking to convert it in Javascript but the principles are the same. Basically, you need to use an accumulator that adds up delta timings, and execute steps based on that. No need to change any physics math or anything, the solution is plug n play. Also has a cool interpolator that removes stuttering and also allows you to do super slow smooth motion (for replays etc.). It's fantastic, works for physics and should work on any step based motion. Basically all you need for accurate timing game motion is there.

You can synhronize your animation with system time.

Save current system time in variable. On the all of frames then you want to redraw picture check if current time - your variable equal some delta time. then redrow your animation. else wait this difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!