引见
- 此篇文章翻译自paul_irish( 就任于Google Chrome团队工程师)
- 文中提到对requestAnimationFrame的polyfill异常不错,可以直接拿来用
- 原文链接:requestAnimationFrame for Smart Animating
什么是requestAnimationFrame?
你可以用过定时器完成动画(经由过程每隔一段时候去转变元素)。浏览器给我们带来了个好消息“为何不供应一个API给开发者,来使一些事变更高效呢”。requestAnimationFrame就是为动画而生的API,用于转变dom款式、canvas或WebGL。
我为何要运用它?
浏览器可以将并发动画优化为单个事宜流和重绘周期中,从而更流通。比方同时举行的以下使命:基于js的动画、css动画、SVG SMIL。而且,当正在实行动画的标签页不可见时,浏览器并不会一向运转它,这就意味着更少的CPU、 GPU和内存的运用,从而延伸电池寿命。
天啦噜,我可以揄扬本身的网站对电池更友爱?
是的大兄弟Totes McGoats(这人跟作者是啥关联~)
我应当怎样运用它?
下面这段是一个简朴的requestAnimationFrame兼容写法,当浏览器不支持时回退到setTimeout的完成体式格局:
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// usage:
// instead of setInterval(render, 16) ....
(function animloop(){
requestAnimFrame(animloop);
render();
})();
// place the rAF *before* the render() to assure as close to
// 60fps with the setTimeout fallback.
越发硬朗的polyfill
以下代码是Opera工程师Erik Möller所写越发硬朗的polyfill。你可以浏览下,尤其是在处置惩罚4-16ms的延迟时候这段代码,从而使帧率更靠近60fps。你会喜好上它的,请注意他运用的规范要领名。我同时也修改了cancel要领称号(WebKit内核的浏览器已更悛改)。
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
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);
};
}());
来看看它的结果
http://jsfiddle.net/XQpzU/435…
requestAnimationFrame API
window.requestAnimationFrame(function(/* time */ time){
// time ~= +new Date // the unix time
});
该回调函数将当前时候作为参数通报,也恰是你说须要的。
(此文写于2011年,下面引见了差别浏览器完成上的差别)
Is it ready?
Right now, the Webkit implementation (available in Nightly Safari and Chrome Dev Channel) and the Mozilla one (available in FF4) differ slightly. Mozilla’s has a bug which caps potential framerates at about 30fps.Actually, “It’s currently capped at 1000/(16 + N) fps, where N is the number of ms it takes your callback to execute. If your callback takes 1000ms to execute, then it’s capped at under 1fps. If your callback takes 1ms to execute, you get about 60fps.” (thx, Boris) It’ll be fixed though, probably for the next release after FF4 ships. Also Chrome 10 doesn’t have the time parameter (added in m11), FF currently ignores the element argument.