39th Lesson: Requestanimationframe Detailed

Source: Internet
Author: User

Everyone should know that if a page runs a lot of timers, no matter how you optimize, it will definitely exceed the specified time to complete the animation. The more timers, the more serious the delay.

To this end, the Yui,kissy, such as the use of central queue, the timer reduced to one. The browser vendor natively supports the Requestanimationframe method, which basically guarantees a refresh of 60 times per second. However, before the standard is established, many low-version browsers are unsupported, such as IE9 and the following versions, but both Google and Firefox implement the Requestanimationframe method with a proprietary method name. For example: Google: Webkitrequestanimationframe,, Firefox: Mozrequestanimationframe. After the standard is formed, IE10 only begins to support it, because IE10 supports the standard Requestanimationframe method, so it does not have a private prefix, so there is no msrequestanimationframe.

Let's first look at how the Requestanimationframe method is used.

var starttime,duration = 3000,requestid;

The function animate (now) { //webkitrequestanimationframe method passes an argument to the callback function for the current time.

var per = (now-starttime)/duration;

if (per >=1) {

  End of animation

}else{

Div.style.left = Math.Round (600*per) + "px";

Window.webkitrequestanimationframe (animate); //This method call will only redraw one animation at a time, and if continuous animation is required, repeat calls

}

}

function Start () {

StartTime = Date.now ();

RequestID = Window.webkitrequestanimationframe (animate); //This method can pass in two parameters, the first is a callback, the second is an element node that performs the animation (optional), and an ID is returned.

}

Div.onclick = start;

The above example is for Chrome browser implementation.

So, how do we write the compatibility notation?

First version:

Window.requestanimationframe = (function () {

return Window.requestanimationframe | | //ie10 and above version, as well as the latest Google, Firefox version

Window.webkitrequestanimationframe | | //Google old version

Window.mozrequestanimationframe | | //Firefox old version

Function (callback) { //IE9 and the following versions

Window.settimeout (callback, 1000/60); //This force lets the animation refresh 60 times a second, the reason is set to 16.7 milliseconds to refresh once, because Requestanimationframe default is also 16.7 milliseconds refresh once.

}

})();

The above compatibility, there are a few questions, the first: there is no solution to the Cancelanimationframe method of compatibility. The second: Force let ie9-browser, animation drawing interval is 16.7ms, but these browsers draw interval is not all this value. The third: The old version of Firefox Mozrequestanimationframe method with the standard Requestanimationframe method to achieve some discrepancies, such as: Early Firefox this method, does not support the transfer of parameters. Fourth: The old version of WebKit, in some versions, this method does not return the ID, and some versions do not give the callback function the current time parameters.

My understanding: As for the old version of Firefox and the old version of WebKit, I personally feel there is no need to go compatible, as long as the compatible ie9-browser is OK. So the above 4 problems only exist in the first two. So if you want to be compatible with the third and fourth questions, please go to the Masaki based on the user's flexor and Lunar shadow version of the improved version: https://github.com/wedteam/qwrap-components/blob/master/ Animation/anim.frame.js.

The second version addresses the first and second questions above:

(function () {
var lasttime = 0;
var version = [' WebKit ', ' Moz '];
For (var i = 0; i < version.length &&!window.requestanimationframe; i++) { //If this browser does not support Requestanima Tionframe method, loops through the version array
window.requestanimationframe = window[version[i] + ' requestanimationframe '];
window.cancelanimationframe = window[version [i] + ' cancelanimationframe '] | | //There are some WebKit versions where the name of this method has changed
window[version [i] + ' cancelrequestanimationframe '];
}

if (!window.requestanimationframe) { //If it is ie9-browser
window.requestanimationframe = function (callback, Element) { //We use the previous example to illustrate this code. When we click on the div, we trigger the Start method, we assume the current time is 11111, set the starttime=11111, call the Requestanimationframe (animate) method, and the current time, We assume that currtime = 11112,lasttime = 0, at this point timetocall = 0, so call settimeout (function () {},0), put lasttime = 11111, return the ID. After the minimum time of the browser, we assume that it is 4ms, and we will immediately execute animate (11112). This will continue to execute the requestanimationframe. If the current time is 11118,timetocall = 9.7, then Lasttime = 11127.7 and the current time is 11127.7, animate (11127.7) is performed, per = 16.7/ 3000, continue to execute requestanimationframe ....
var currtime = new Date (). GetTime ();
var timetocall = Math.max (0, 16.7-(currtime-lasttime)); the value of//timetocall is between 0-16.7.


callback (currtime + timetocall);

Lasttime = Currtime + timetocall;
return ID;
};

if (!     Window.cancelanimationframe) {  
Window.cancelanimationframe = function (id) {
cleartimeout (ID);
};

Of course, requestanimationframe is not without shortcomings, it can not control fps (60), we can not use in the following scenarios. For example: Do some slow-release action, Fps<60 case, and in the action, shootout, rook and other scenes, FPS needs >60 case, like this scenario, if the frame number is not high, the screen will be blurred. With settimeout (Ie9,10,firefox,chrome, etc., its shortest time interval has been compressed to 4ms) we can easily run to more than 100 frames of animation, can make the picture clearer, more realistic details.

In addition, PostMessage this asynchronous method, can achieve ultra-high animation, someone has done experiments:

SetTimeout average number of frames 200

Requestanimationframe average number of frames 60

Loop (loop) average number of frames 200-300

PostMessage average number of frames 900-1000

var testing = true; //used to stop the animation, that is, stop code execution

function Main () {

 Record the interval of two execution times

}

function run1 () { //click button 1, execute the Run1 method, and then use the SetTimeout method to continually execute the main method, the main method records the time of each execution, and the interval of two execution time is calculated.

Main ();

if (testing) {

SetTimeout (RUN1, 1);

}

}

function run2 () { //click button 2, execute Run2 method

Main ();

if (testing) {

Window.requestanimationframe (RUN2);

}

}

function Run3 () { //click button 3, execute Run3 method

var count = 15;

while (count--) { //uses the while loop to execute the main method, recording the time interval between two loop operations.

Main ();

}

if (testing) {

SetTimeout (run3,1); //Of course there will be a little bit of error here, because the SetTimeout method is used, so we can set Testing=false, stop the loop call main, and if you use while (true), you cannot stop this loop.

}

}

Window.addeventlistener ("message", Run4,false); //Binds the message event, and whenever the PostMessage method is called, the message event is triggered.

function Run4 () {

Main ();

if (testing) {

Window.postmessage ("", "*");

}

}

IE10 also has an efficient asynchronous method of Setimmediate.

In reality, especially in game development, we want to combine multiple asynchronous APIs. For example: As the background of trees, water and other uses Requestanimationframe method, player role, due to the need for speed changes, then use settimeout more appropriate, some very dazzling animation, may need to postmessage,setimmediate , Image.onerror and other APIs.

Come on!

39th Lesson: Requestanimationframe 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.