Table of Contents
Advantages
Use
Compatibility
Home Web Front-end H5 Tutorial HTML5 optimized web animation—requestAnimationFrame

HTML5 optimized web animation—requestAnimationFrame

Feb 27, 2017 pm 03:22 PM


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>
Copy after login
#demo {    width: 0;    height: 100px;    background-color: orange;}
Copy after login

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);
Copy after login

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);
Copy after login

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);
          };
})();
Copy after login

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);
    };}());
Copy after login

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;
    }
}());
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles