Principles and examples of JavaScript animation implementation

Source: Internet
Author: User
Tags current time setinterval

Suppose there is such an animated feature requirement: Change the width of a div from 100px to 200px. The written code might be like this:

The code is as follows Copy Code

<div id= "test1" style= "width:100px; height:100px; Background:blue; Color:white; " ></div>
function animate1 (element, Endvalue, duration) {
var starttime = new Date (),
Startvalue = parseint (element.style.width),
Step = 1;

var Timerid = setinterval (function () {
var nextValue = parseint (element.style.width) + step;
Element.style.width = nextValue + ' px ';
if (NextValue >= endvalue) {
Clearinterval (Timerid);
Show animation time consuming
element.innerhtml = new Date-starttime;
}
}, Duration/(endvalue-startvalue) * step);
}

Animate1 (document.getElementById (' test1 '), 200, 1000);

The principle is to increase the 1px at a certain time until 200px. However, the animation after the end of time to display more than 1s (usually 1.5s or so). The reason is because the setinterval does not strictly guarantee the execution interval.

Is there any better way to do it? Let's take a look at a primary school math problem:

A building and B floor 100 meters apart, a person from a building to walk to the B floor, 5 minutes to go to the destination, ask the first 3 minutes he distance from a building how far?

The formula for calculating a certain time distance in uniform motion is: distance * Current time/time. So the answer should be 100 * 3/5 = 60.

The inspiration of this problem is that the distance of a certain time can be calculated by a specific formula. Similarly, the value of a moment in the animation process can also be calculated from a formula, rather than accumulating:

The code is as follows Copy Code

<div id= "test2" style= "width:100px; height:100px; background:red; Color:white; " ></div>
function Animate2 (element, Endvalue, duration) {
var starttime = new Date (),
Startvalue = parseint (element.style.width);

var Timerid = setinterval (function () {
var percentage = (new Date-starttime)/duration;

var stepvalue = Startvalue + (endvalue-startvalue) * percentage;
Element.style.width = stepvalue + ' px ';

if (percentage >= 1) {
Clearinterval (Timerid);
element.innerhtml = new Date-starttime;
}
}, 13);
}

Animate2 (document.getElementById (' test2 '), 200, 1000);

After this improvement, you can see that the animation execution takes up to only 10 ms errors. However, the problem has not been fully resolved, in the Browser development tool to check the TEST2 elements can be found that test2 the final width may be more than 200px. The code that carefully examines the ANIMATE2 function can find:

The value of the percentage may be greater than 1, which can be resolved by Math.min limit maximum value.
Even if the value of the percentage is not greater than 1, as long as the Endvalue or Startvalue is decimal, the (endvalue-startvalue) * Percentage value may also produce errors because the JavaScript decimal operation is not accurate enough. In fact, we want to ensure that the final value of the accuracy, so in the percentage 1, the direct use of endvalue can be.
The code for the ANIMATE2 function is then modified to:

The code is as follows Copy Code

function Animate2 (element, Endvalue, duration) {
var starttime = new Date (),
Startvalue = parseint (element.style.width);

var Timerid = setinterval (function () {
Guaranteed percentage not greater than 1
var percentage = Math.min (1, (New Date-starttime)/duration);

        var Stepvalue;
        if (percentage >= 1) {
            //guarantee the accuracy of the final value
             Stepvalue = Endvalue;
       } else {
             Stepvalue = Startvalue + (endvalue-startvalue) * percentage;
       }
        element.style.width = stepvalue + ' px ';

if (percentage >= 1) {
Clearinterval (Timerid);
element.innerhtml = new Date-starttime;
}
}, 13);
}

There is one last question: Why is the interval of setinterval set to 13MS? The reason is that the current display refresh rate is generally not more than 75Hz (that is, 75 times per second refresh, that is, every about 13ms refresh once), the interval with the refresh rate synchronization effect better.

Related Article

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.