Home  >  Article  >  Web Front-end  >  HTML5 optimized web animation—requestAnimationFrame

HTML5 optimized web animation—requestAnimationFrame

黄舟
黄舟Original
2017-02-27 15:22:201860browse


We have many choices to implement animation in the page
You can use CSS3 transition
Animation in CSS3 cooperates with keyframes rules
SMIL can also be used in SVG- animation
The most original method is that we use JavaScript's setTimeout/setInterval to implement animation
But now we have another method
requestAnimationFrame

Advantages

requestAnimationFrame The principle and usage are similar to setTimeout/setInterval
It implements animation in a recursive form
Since it is specially used for web animation, it must have its own advantages


Using setTimeout/setInterval to create animations has the following disadvantages

  • The accuracy of ms cannot be guaranteed (JavaScript is single-threaded and may cause blocking)

  • There is no optimization of the loop mechanism for calling animation

  • It does not take into account the best time to draw animation (just simply call the loop at a certain time)

In contrast, requestAnimationFrame has the following advantages

  • The animation is smoother and optimized by the browser (executed once before the page is refreshed)

  • The window is not When activated, the animation is paused, effectively saving CPU overhead

  • Power saving, very friendly to mobile terminals

Use

requestAnimationFrame Like setTimeout/setInterval,
are all methods on window
, so we can use
requestAnimationFrame() directly
The parameter is a callback function, inside the function we need to change the element style
and need Manually execute the callback
Also returns a handle
Pass in cancelAnimationFrame to cancel it
See an example


Now we want to make an element in the page wider

<p id="demo"></p>
#demo {    width: 0;    height: 100px;    background-color: orange;}

Let’s first look at the implementation of setInterval

var demo = document.getElementById(&#39;demo&#39;);
var len = 0;var timerFunc = function(){    len += 5;    if(len <= 200){
        demo.style.width = len + &#39;px&#39;;     
    }else{
        clearInterval(timer);
    }
}var timer = setInterval(timerFunc, 20);

The animation implemented by requestAnimationFrame

var demo = document.getElementById(&#39;demo&#39;);var len = 0;
var timerFunc = function(){    len += 5;    if(len <= 200){
        demo.style.width = len + &#39;px&#39;;
        requestAnimationFrame(timerFunc); /*执行回调*/
    }else{
        cancelAnimationFrame(timer); 
    }
}var timer = requestAnimationFrame(timerFunc);

We can find that the animation displayed by our requestAnimationFrame is very smooth

Compatibility

Since it is a relatively new thing, it is inevitable that there will be compatibility issues with various browsers
But the current browsers already support it very well

We can write a polyfill for it

window.requestAnimationFrame = (function(){  
return  window.requestAnimationFrame       ||          
window.webkitRequestAnimationFrame ||          
window.mozRequestAnimationFrame    ||          
function(callback){            
window.setTimeout(callback, 1000 / 60);
          };
})();
window.requestAnimationFrame = (function(){  
return  window.cancelAnimationFrame       ||          
window.webkitCancelAnimationFrame ||          
window.mozCancelAnimationFrame    ||          
function(ID){            
window.clearTimeout(ID);
          };
})();

If this browser really has nothing
then it can only fallback and use setTimeout and clearTimeout


The above is just a simple polyfill
But the master has written a better one
You can also unify the prefixes of various browsers

(function() {
    var lastTime = 0;
    var vendors = [&#39;ms&#39;, &#39;moz&#39;, &#39;webkit&#39;, &#39;o&#39;];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + &#39;RequestAnimationFrame&#39;];
        window.cancelAnimationFrame = window[vendors[x] + &#39;CancelAnimationFrame&#39;] || window[vendors[x] + &#39;CancelRequestAnimationFrame&#39;];
    }
    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);
    };}());

Later there will be updates
Relevant js can be Click here
github original address

if (!Date.now)    
Date.now = function() { return new Date().getTime(); };

(function() {    &#39;use strict&#39;;    
var vendors = [&#39;webkit&#39;, &#39;moz&#39;];    
for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {        
var vp = vendors[i];
        window.requestAnimationFrame = window[vp+&#39;RequestAnimationFrame&#39;];
        window.cancelAnimationFrame = (window[vp+&#39;CancelAnimationFrame&#39;]
                                   || window[vp+&#39;CancelRequestAnimationFrame&#39;]);
    }    if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
        || !window.requestAnimationFrame || !window.cancelAnimationFrame) {        
        var lastTime = 0;
        window.requestAnimationFrame = function(callback) {
            var now = Date.now();            
            var nextTime = Math.max(lastTime + 16, now);            
            return setTimeout(function() { callback(lastTime = nextTime); },
                              nextTime - now);
        };
        window.cancelAnimationFrame = clearTimeout;
    }
}());

Interested students can study it

The above is the content of HTML5 optimized Web animation-requestAnimationFrame. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn