Requestanimationframe Animation Control Detailed

Source: Internet
Author: User

Front-end development whqet,csdn, Wang Haiqing, Whqet, front-end development experts

Still using setinterval, you out, requestanimationframe can achieve more economical, more accurate control animation, today to see its ins and outs.

------------------------------------------------------------

--I participated in the blog star selection, if you like my blog, to vote, your support is my source of power, go!

--------------------------------------------------------------------------------------------------------------- --

Past

In Web animations, app animations, we often animate the DOM and CSS by setinterval or settimeout, as shown in the following code.

var timer=setinterval (function () {   //Some animation},1000/60)//Clear animation clearinterval (timer);

However, the way the animation is very resource-intensive, often the result, just beginning more fluent, 5 minutes after the animation is stuck, so "everyone" can not see, and began to think of this approach.

Brief introduction

About 2011 years, Paul Irish's "Requestanimationframe for Smart animating" first introduced the use of Requestanimationframe, and then after everyone's efforts, "Timing Control for script-based animations became the candidate standard for the world of the world in 2013.

The advantages of the requestanimationframe approach are as follows:

1. Browser-optimized, more smooth animation

2. When the window is not activated, the animation will stop, save the compute resources

3. More power saving, especially for mobile terminals

Requestanimationframe, the simple calling code is as follows.

function animate () {  //do whatever  requestanimationframe (animate);  Do something animate  }//go->requestanimationframe (animate);

Sometimes we have to add some control,Requestanimationframe can also return a handle like setinterval, and then we can cancel it. The control animation code is as follows.

var globalid;function animate () {  //do whatever  globalid=requestanimationframe (animate);  Do something animate  }//when ot startglobalid=requestanimationframe (animate);//when to Stopcancelanimationframe (GlobalID);

All right, let's finish the presentation. Don't go, for a front-end developer, we can not be so "simple", because the browser is too willful, who knows how these browsers are "thinking", we have to look at the browser compatibility situation. Come on Caniuse.


Desktop side except for the evil IE series Low version 9-, mobile side except Opera Mini and Android browser4.3-other support. Total support rate of 83.38%, no prefix support rate of 81.98%, the support rate is good. As a full-on front-end er, we have to continue to save those who "have no money, the right hand but elm knots, but also in the use of low-version browser" of the compatriots, to a polyfill.

Patch

Paul Irish's simplified version of the patch, patched and used as shown in the following code.

Patch Window.requestanimationframe = (function () {  return  window.requestanimationframe       | |          Window.webkitrequestanimationframe | |          Window.mozrequestanimationframe    | |          Function (callback) {            window.settimeout (callback, 1000/60);          };}) ();//Use (function animate () {  requestanimationframe (animate);  Animation}) ();

This patch can be better compatible with browsers that support this feature, but for unsupported? Here's how to add, how to stop it? So our patch has to go on ...

(function () {var lasttime = 0;      var vendors = [' ms ', ' Moz ', ' webkit ', ' o ']; for (var x = 0; x < vendors.length &&!window.requestanimationframe; ++x) {Window.requestanimationfram          E = 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, +-(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);          }; }());

There are later, there is a new update, everyone to GitHub to view the details, code to paste, we study.

Requestanimationframe Polyfill by Erik m?ller.//Fixes from Paul Irish, Tino Zijdel, Andrew Mao, Klemen Slavi?, Darius bacon//MIT Licenseif (!        Date.now) Date.now = function () {return new Date (). GetTime ();};(function () {' Use strict ';    var vendors = [' WebKit ', ' Moz '];        for (var i = 0; i < vendors.length &&!window.requestanimationframe; ++i) {var VP = vendors[i];        Window.requestanimationframe = window[vp+ ' requestanimationframe ']; Window.cancelanimationframe = (window[vp+ ' cancelanimationframe ') | | window[vp+ ' CANCELREQ    Uestanimationframe ']); 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 + +, now); Return SetTimeout (function ({Callback (lasttime = Nexttime);}, Nexttime-now);        };    Window.cancelanimationframe = cleartimeout; }}());

Of course, when the actual combat we put these code in a separate file, to download here.

Finally, let's take a particle case and experience it.

References and in-depth reading

1. Paul Irish, requestanimationframe for Smart animating

2. MDN, Window.requestanimationframe ()

3. Chris Coyier, Using requestanimationframe

4. Matt West, efficient animations with requestanimationframe

5. CR, Timing control for script-based animations

6. Polyfill for Requestanimationframe/cancelanimationframe

7. Zhang Xin Xu, CSS3 animation so strong, requestanimationframe and yarn use?

8. Ju Yongsheng, Understanding WebKit and Chromium: Render main loop (main loop) and Requestanimationframe

Thank you for your patience, if you have any help, please support me

----------------------------------------------------------

Front-end development Whqet, focus on web front-end development, share related resources, welcome to praise, welcome to shoot bricks.

---------------------------------------------------------------------------------------------------------

Requestanimationframe Animation Control Detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.