使用RequestAnimationFrame准确计时 [英] Accurate Timing with RequestAnimationFrame

查看:615
本文介绍了使用RequestAnimationFrame准确计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我还没有找到关于这个主题的大量文档。我得到的一般感觉是,在为浏览器实现动画时,最好使用RequestAnimationFrame而不是bog标准JavaScript计时器。我的理解是定时器不可靠,并且它们的分辨率可能因不同的浏览器而异。

I've not found a lot of documentation on this subject so far. The general feel I get is when implementing animations for the browser it is better to use RequestAnimationFrame over bog standard JavaScript timers. My understanding is that timers are unreliable and their resolution can vary between different browsers.

我一直在关注这个要点: https://gist.github.com/1114293#file_anim_loop_x.js

I've been looking at this gist: https://gist.github.com/1114293#file_anim_loop_x.js

但我不清楚如何确保动画在固定的时间内发生。例如,我可能想在2秒内从左到右动画一些东西。这是否可以使用RequestAnimationFrame或者它是否能够达到目的?

But it's not clear to me how you can ensure that an animation transpires over a fixed amount of time. For example I might want to animate something from left to right within 2 seconds. Is this do-able using RequestAnimationFrame or does it defeat the purpose?

推荐答案

就是这样,我遇到了类似的问题很久以前,我想出了一种方法,它结合了rAF和performance.now(),它非常有效。

It just so happens, I had a similar problem not long ago and came up with an approach which combines rAF with performance.now() which works very effectively.

我现在可以将定时器精确到大约12位小数:

Im now able to make timers accurate to approx 12 decimal places:

    window.performance = window.performance || {};
    window.performance.now = (function() {
        return performance.now       ||
            window.performance.mozNow    ||
            window.performance.msNow     ||
            window.performance.oNow      ||
            window.performance.webkitNow ||
                function() {
                    return new Date().getTime(); 
                };
        })();

http://jsfiddle.net/CGWGreen/9pg9L/

这篇关于使用RequestAnimationFrame准确计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆