在请求动画填充内的回调参数

Parameter in callback inside request animation polyfill

本文关键字:回调 参数 填充 请求 动画      更新时间:2023-09-26

我阅读了以下请求动画填充。然而,我不明白为什么作者把currTime + timeToCall参数放在setInterval中的callback中:

var id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            },
下面是完整的多边形代码片段:
// Set up requestAnimationFrame and cancelAnimationFrame for use in the game code
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame =
        window[vendors[x] + 'CancelAnimationFrame'] ||
        window[vendors[x] + 'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            },
            timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

填料中的此参数用于覆盖requestAnimationFrame规格。如果你打算在你的动画中使用时间控制,你的回调应该提供一个时间戳参数。polyfill中的(currTime + timeToCall)为动画提供了比简单使用setTimeout更准确的时间戳。

var now, timeBetweenFrames, lastTime;
function animation (timestamp) {
  now  = timestamp; // the value of timestamp is changing
  timeSinceLastFrame = now - lastTime; // time between frames in miliseconds
  lastTime = now;       
  // ... performe your animations
  // you can use the timeSinceLastFrame value, for example, 
  // to interpolate the position of your objects,
  // making the animation reacts equally, independent of performance scenarios
  // here is an example:
  // ... 
  // if you have an object named player, with moves depending on his velocity
  // update the player position
  player.x += player.velocity.x * (timeSinceLastFrame/1000);
  player.y += player.velocity.y * (timeSinceLastFrame/1000);
  // note that timeSinceLastFrame/1000 is the time in seconds instead of miliseconds
  // draw the player on the screen
  player.draw();
  // ...
  requestAnimationFrame(animation);
}
function start() {
  lastTime = Date.now() // or performance.now() like described below this code snippet
  requestAnimationFrame(animation);  // let this party begin
}
start();

请注意,如果浏览器具有本机requestAnimationFrame支持,则发送给回调的timestamp参数的时间格式与performance.now()相同,而不是Date.now()。这对于某些新版本的浏览器(如Chrome)是有效的。有关HTML5 Rocks的详细解释,请参阅这篇文章:http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision