javascript - 最新的 requestAnimationFrame polyfill

标签 javascript html requestanimationframe

http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision告诉我最近(Chrome 20)requestAnimationFrame 获得了一个新的亚毫秒精度计时器,我必须更新我的代码以支持它。

环顾周围的各种 polyfill,它们似乎都早于此更新。它们是否以某种方式起作用(我不这么认为),或者根本没有可用的最新版本?我应该自己做计时吗(看起来有点浪费)。

最佳答案

我也刚读过那篇文章,很想亲自尝试一下。我试过在不支持高分辨率计时器的浏览器中向 rAF 回调添加包装器。它使用 Paul Irish 的原始 polyfill 并添加了以下行:

var hasPerformance = !!(window.performance && window.performance.now);

// Add new wrapper for browsers that don't have performance
if (!hasPerformance) {
    // Store reference to existing rAF and initial startTime
    var rAF = window.requestAnimationFrame,
        startTime = +new Date;

    // Override window rAF to include wrapped callback
    window.requestAnimationFrame = function (callback, element) {
        // Wrap the given callback to pass in performance timestamp
        var wrapped = function (timestamp) {
            // Get performance-style timestamp
            var performanceTimestamp = (timestamp < 1e12) 
                ? timestamp 
                : timestamp - startTime;

            return callback(performanceTimestamp);
        };

        // Call original rAF with wrapped callback
        rAF(wrapped, element);
    }        
}

以下是所有内容的要点以及使用新代码的更新示例:

https://gist.github.com/4078614

http://jsfiddle.net/timhall/XQpzU/4351/

此方法旨在将传递到回调函数的参数规范化为高分辨率计时器格式。您可以使用类似的方法(恰恰相反)将高分辨率计时器转换为旧格式(如果您的现有代码需要这样做),但我认为这是一种回归。

我将在我目前正在进行的一个项目中尝试它,如果我发现任何问题/改进,我将更新要点。

关于javascript - 最新的 requestAnimationFrame polyfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13241314/

相关文章:

javascript - AngularFire - Firestore - 如何获取子集合并合并到 HTML 中

php - 对齐标签字段 symfony

javascript - 我可以多次调用 requestAnimationFrame 吗?

javascript - 如何控制动画速度(requestAnimationFrame)?

javascript - 为什么在循环开始时调用 requestAnimationFrame 不会导致无限递归?

Javascript - 针对单个参数执行一组函数

javascript - highcharts 不会渲染到我的 div

javascript - 在 Windows 8 Javascript 中关闭相机的正确方法是什么?

asp.net - 如何获得标签控件的默认字体名称?

javascript - FA 图标没有出现在我的 html 元素的第二页中。怎么修?