Requestanimationframe polyfill 参数
Requestanimationframe polyfill argument
我有 2 个关于 requestanimationframe polyfill 函数的问题:
1)为什么 element
作为参数包含在 window.requestAnimationFrame=function(callback, element)
中?
2)这里为什么用16:var timeToCall =Math.max(0, 16 - (currTime - lastTime));
?是否取决于程序员的判断,不是太大也不是太低,因为我们从中减去 currTime-lastTime?
(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);
};
}());
正如Hacketo所述,element确实不是window.requestAnimationFrame的参数,它只需要回调函数。
其次,16 用于确定最大 FPS。 setTimeout 函数的触发速度不会超过每秒 60 次。然而,这是一种脆弱的游戏同步方法。 This article 描述了一个很好的方法。
我有 2 个关于 requestanimationframe polyfill 函数的问题:
1)为什么 element
作为参数包含在 window.requestAnimationFrame=function(callback, element)
中?
2)这里为什么用16:var timeToCall =Math.max(0, 16 - (currTime - lastTime));
?是否取决于程序员的判断,不是太大也不是太低,因为我们从中减去 currTime-lastTime?
(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);
};
}());
正如Hacketo所述,element确实不是window.requestAnimationFrame的参数,它只需要回调函数。
其次,16 用于确定最大 FPS。 setTimeout 函数的触发速度不会超过每秒 60 次。然而,这是一种脆弱的游戏同步方法。 This article 描述了一个很好的方法。