The requestAnimationFrame function is used to write the easing function. I have learned about it before, but I always feel that I don’t understand it very well, so I translated an article written by a foreigner for the purpose of learning and sharing.
What is requestAnimationFrame?
In the past, when we did animation, we needed a timer to make some changes every millisecond. Now there is good news: browser manufacturers have decided to provide a method specifically for animation, namely requestAnimationFrame(), and it can also be better optimized at the browser level. However, this is only a basic API for animation, that is, it is not based on style changes of DOM elements, nor is it based on canvas or WebGL. Therefore, we need to write the specific animation details ourselves.
Why should we use it?
For n animations running at the same time, the browser can optimize and optimize the original N times of reflow and repaint into 1 time, thus achieving high-quality animation. For example, there are JS-based animations, CSS-based transitions, or SVG SMIL. Plus. If a tab in the browser is running such an animation, and then you switch to another tab, or simply minimize it, In short, if you can't see it, the browser will stop the animation. This will mean less CPU, GPU and less memory consumption, resulting in significantly longer battery life.
How to use it?
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame | |
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// usage:
// instead of setInterval(render, 16) ....
(function animloop(){
render();
requestAnimFrame(animloop, element);
})();
Note: I used "requestAnimFrame" here because the specification is still changing and I don't want to be at the mercy of the specification.
requestAnimationFrame API
window.requestAnimationFrame(function(/ * time */ time){
// time ~= new Date // the unix time
}, /* optional bounding elem */ elem);
Give Chrome first and Firefox version
window.mozRequestAnimationFrame([callback]) ; // Firefox
window.webkitRequestAnimationFrame(callback[, element]); // Chrome
Parameters:
callback: (FF optional, Chrome required)
Next The function called by repaint, the first parameter of the function is the current time
element: (FF None)
Let’s paraphrase it: it is actually the canvas, and the ‘painting’ is animation. (the element that visually bounds the entire animation). For canvas and WebGL, it is the