Home Web Front-end JS Tutorial A brief analysis of the implementation principles of Javascript animation_javascript skills

A brief analysis of the implementation principles of Javascript animation_javascript skills

May 16, 2016 pm 04:11 PM
javascript animation Implementation principle

Suppose there is such an animation function requirement: change the width of a div from 100px to 200px. The code written may look like this:

Copy code The code is as follows:


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);
// It takes time to display the animation
                element.innerHTML = new Date - startTime;
}
}, duration / (endValue - startValue) * step);
}

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


The principle is to increase 1px at regular intervals until it reaches 200px. However, the display time after the animation ends is more than 1s (usually about 1.5s). The reason is that setInterval does not strictly guarantee the execution interval.

Is there a better way? Let’s take a look at a primary school math problem:

Copy code The code is as follows:

Building A and Building B are 100 meters apart. A person walks from Building A to Building B at a constant speed and walks for 5 minutes to reach the destination. How far is he from Building A at the third minute?

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

The inspiration brought by this question is that the distance at a certain moment can be calculated through a specific formula. In the same way, the value at a certain moment during the animation process can also be calculated through a formula instead of accumulating:

Copy code The code is as follows:


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 time will only have an error of 10 ms at most. But the problem has not been completely solved. Checking the test2 element in the browser development tool shows that the final width of test2 may be more than 200px. Careful inspection of the code of the animate2 function reveals:

The value of 1.percentage may be greater than 1, which can be solved by limiting the maximum value through Math.min.
2. Even if it is guaranteed that the value of percentage is not greater than 1, as long as endValue or startValue is a decimal, the value of (endValue - startValue) * percentage may still produce errors because the precision of Javascript decimal operations is not enough. In fact, what we want to ensure is the accuracy of the final value, so when the percentage is 1, just use endValue directly.

So, the code of animate2 function is modified to:

Copy code The code is as follows:

function animate2(element, endValue, duration) {
var startTime = new Date(),
         startValue = parseInt(element.style.width);

var timerId = setInterval(function() {
​​​​ // Ensure that the percentage is not greater than 1
      var percentage = Math.min(1, (new Date - startTime) / duration);

var stepValue;
If (percentage >= 1) {
​​​​​​ // Ensure 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 refresh rate of current monitors generally does not exceed 75Hz (that is, refreshed 75 times per second, that is, refreshed every about 13ms). It is better to synchronize the interval with the refresh rate.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Animation not working in PowerPoint [Fixed] Animation not working in PowerPoint [Fixed] Feb 19, 2024 am 11:12 AM

Are you trying to create a presentation but can't add animation? If animations are not working in PowerPoint on your Windows PC, then this article will help you. This is a common problem that many people complain about. For example, animations may stop working during presentations in Microsoft Teams or during screen recordings. In this guide, we will explore various troubleshooting techniques to help you fix animations not working in PowerPoint on Windows. Why aren't my PowerPoint animations working? We have noticed that some possible reasons that may cause the animation in PowerPoint not working issue on Windows are as follows: Due to personal

How to set up ppt animation to enter first and then exit How to set up ppt animation to enter first and then exit Mar 20, 2024 am 09:30 AM

We often use ppt in our daily work, so are you familiar with every operating function in ppt? For example: How to set animation effects in ppt, how to set switching effects, and what is the effect duration of each animation? Can each slide play automatically, enter and then exit the ppt animation, etc. In this issue, I will first share with you the specific steps of entering and then exiting the ppt animation. It is below. Friends, come and take a look. Look! 1. First, we open ppt on the computer, click outside the text box to select the text box (as shown in the red circle in the figure below). 2. Then, click [Animation] in the menu bar and select the [Erase] effect (as shown in the red circle in the figure). 3. Next, click [

After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 Jan 26, 2024 am 09:42 AM

This website reported on January 26 that the domestic 3D animated film "Er Lang Shen: The Deep Sea Dragon" released a set of latest stills and officially announced that it will be released on July 13. It is understood that "Er Lang Shen: The Deep Sea Dragon" is produced by Mihuxing (Beijing) Animation Co., Ltd., Horgos Zhonghe Qiancheng Film Co., Ltd., Zhejiang Hengdian Film Co., Ltd., Zhejiang Gongying Film Co., Ltd., Chengdu The animated film produced by Tianhuo Technology Co., Ltd. and Huawen Image (Beijing) Film Co., Ltd. and directed by Wang Jun was originally scheduled to be released in mainland China on July 22, 2022. Synopsis of the plot of this site: After the Battle of the Conferred Gods, Jiang Ziya took the "Conferred Gods List" to divide the gods, and then the Conferred Gods List was sealed by the Heavenly Court under the deep sea of ​​Kyushu Secret Realm. In fact, in addition to conferring divine positions, there are also many powerful evil spirits sealed in the Conferred Gods List.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Hayao Miyazaki's animated film 'Porco Rosso' has been extended to January 16 next year, with a Douban score of 8.6 Hayao Miyazaki's animated film 'Porco Rosso' has been extended to January 16 next year, with a Douban score of 8.6 Dec 18, 2023 am 08:07 AM

According to news from this site, Miyazaki Hayao's animated film "Porco Rosso" has announced that it will extend the release date to January 16, 2024. This site previously reported that "Porco Rosso" has been launched in the National Art Federation Special Line Cinema on November 17, with a cumulative box office of over 2,000 10,000, with a Douban score of 8.6, and 85.8% of 4 and 5 star reviews. "Porco Rosso" was produced by Studio Ghibli and directed by Hayao Miyazaki. Moriyama Moriyama, Tokiko Kato, Otsuka Akio, Okamura Akemi and others participated in the dubbing. It was originally released in Japan in 1992. The film is adapted from Hayao Miyazaki's comic book "The Age of Airships" and tells the story of the Italian Air Force's ace pilot Pollock Rosen who was magically turned into a pig. After that, he became a bounty hunter, fighting against air robbers and protecting those around him. Plot synopsis: Rosen is a soldier in World War I

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Best Free AI Animation Art Generator Best Free AI Animation Art Generator Feb 19, 2024 pm 10:50 PM

If you are eager to find the top free AI animation art generator, you can end your search. The world of anime art has been captivating audiences for decades with its unique character designs, captivating colors and captivating plots. However, creating anime art requires talent, skill, and a lot of time. However, with the continuous development of artificial intelligence (AI), you can now explore the world of animation art without having to delve into complex technologies with the help of the best free AI animation art generator. This will open up new possibilities for you to unleash your creativity. What is an AI anime art generator? The AI ​​Animation Art Generator utilizes sophisticated algorithms and machine learning techniques to analyze an extensive database of animation works. Through these algorithms, the system learns and identifies different animation styles

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles