In-depth exploration of some methods to make JavaScript animation smoother

Source: Internet
Author: User

In-depth exploration of some methods to make JavaScript animation smoother

This article mainly introduces some methods to make JavaScript animation smooth, including comparison with CSS animation effects. For more information, see

Javascript-based animation has the same effect as CSS transition and even accelerates the transition. How can this happen? The performance of Adobe and Google's continuously released rich media mobile websites is comparable to that of local applications. How can this happen?

This article provides an overview of Javascript-based DOM animation libraries, such as Velocity. js and GSAP, to see how they are more effective than jQuery and CSS animations.

JQuery

Let's start with the basics: JavaScript and jQuery are mistakenly confused. JavaScript animation is fast. jQuery slowed down. Why? Because-although jQuery is very powerful-it has never been jQuery's design goal to become a powerful animation engine:

JQuery cannot avoid layout bumps because its code library provides a variety of functions beyond animation.

JQuery's memory consumption often triggers garbage collection, so that the animation will be frozen from time to time.

JQuery uses setInterval instead of requestAnimationFrame (RAF) to protect new technologies from their own influence.

It should be noted that the layout is not smooth at the beginning of the animation, and garbage collection is the culprit that causes the smoothness during the animation, but not using RAF will lead to a low frame rate.

Implementation example

DOM query and update combinations that avoid layout bumps:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Var currentTop,

CurrentLeft;

 

/* With layout thrashing .*/

CurrentTop = element. style. top;/* QUERY */

Element. style. top = currentTop + 1;/* UPDATE */

 

CurrentLeft = element. style. left;/* QUERY */

Element. style. left = currentLeft + 1;/* UPDATE */

 

/* Without layout thrashing .*/

CurrentTop = element. style. top;/* QUERY */

CurrentLeft = element. style. left;/* QUERY */

 

Element. style. top = currentTop + 1;/* UPDATE */

Element. style. left = currentLeft + 1;/* UPDATE */

The query that occurs after the update will force the browser to re-calculate the computed data on the page (the new update effect will also be taken into account ). this will produce significant overhead for the animation, which is only a 16-millisecond interval running timeout.

Similarly, implementing RAF does not have to be a significant rework on your existing code base. let's compare it with the basic implementation of RAF:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Var startingTop = 0;

 

/* SetInterval: Runs every 16 ms to achieve 60fps (1000 ms/60 ~ = 16 ms ).*/

SetInterval (function (){

/* Since this ticks 60 times a second, we divide the top property's increment of 1 unit per 1 second by 60 .*/

Element. style. top = (startingTop ++ = 1/60 );

}, 16 );

 

/* RequestAnimationFrame: Attempts to run at 60fps based on whether the browser is in an optimal state .*/

Function tick (){

Element. style. top = (startingTop ++ = 1/60 );

}

 

Window. requestAnimationFrame (tick );

RAF has the greatest possibility of promoting animation performance. You can make a single change to your code.

CSS Conversion

CSS conversion surpasses jQuery by throwing the animation logic to the browser itself, which is effective in the following aspects: (1) optimize DOM interaction and memory consumption to avoid freezing (bumps). (2) use the RAF principle of the engine. (3) force hardware acceleration (use GPU capabilities to improve animation performance ).

However, the reality is that these optimizations can also be executed directly in JavaScript. GSAP has been doing this for many years. Velocity. js, a new animation engine, not only utilizes the same technology, but also takes a few more steps forward-we will explore these soon.

In the face of the facts, the competition between JavaScript animation and CSS conversion is only the first step in our rehabilitation plan. The second step is to implement "JavaScript animation can actually be faster than CSS conversion ".

Now let's talk about the weakness of CSS Transformation:

Transition forces hardware acceleration to increase GPU consumption, resulting in poor running at high loads. This situation is especially evident on mobile devices. (In special cases, for example, the bottleneck caused by data transmission between the main browser thread and the typographical thread will also lead to LD ). Some CSS attributes, such as transform and opacity, are not affected by these bottlenecks. Adobe has carefully summarized these issues here.

Transition is useless under IE10, and the desktop site availability problems caused by IE8 and IE9 are still widespread.

Since transition is not controlled by JavaScript native (but only by JavaScript), the browser cannot know how to optimize them in sync with the JavaScript code that controls the transition.

On the contrary, JavaScript-based animation libraries can determine the appropriate hardware to enable. They are native to support various versions of IE browsers, and they are especially suitable for batch animation optimization.

My advice is to use native CSS transform only when you develop a mobile client and only implement simple animations. In this environment, transition is a native and effective solution that enables you to implement all the animation logic in the style sheet without adding additional JavaScript libraries, this prevents your page from becoming bloated. However, when you are designing complex UIS or developing apps with UIS in different states, you should use the animation library to keep the animation smooth and make the workflow easy to manage. Transit is a library that is particularly outstanding in managing CSS transformations.

JavaScript Animation

Okay, so JavaScript has a higher performance. But how much faster is Javascript? Okay-initially-it is fast enough to build a real 3D animation example. Generally, during the build, you will only see that WebGL is used. it is enough to build a small Multimedia Animation. Generally, you can see that only Flash or After Effects are used. building a virtual world is enough. Generally, you only need to see the canvas.

To compare the leading animation library with Transit (which uses CSS gradient effects), let's look back at the Velocity documentation on VelocityJS.org.

The question remains: how does JavaScript achieve its high level of performance? The following is a brief list of optimizations for Javascript-based animation that can be executed:

Synchronize DOM → stack the entire animation chain to minimize layout jitter.

Cache attribute values for the entire chain call to minimize DOM queries (these are the pitfalls of high-performance DOM animation ).

Cache the unit conversion rate (such as px to %, em, etc.) of the entire element in the same call .).

If an update is not visually visible, the style update is skipped.

Review the previous knowledge about layout bumps, Velocity. js uses these best practices to cache the animation end value and reuse it as the start value of the subsequent animation. This avoids re-querying the DOM to get the starting value of the element:

?

1

2

3

4

5

$ Element

/* Slide the element down into view .*/

. Velocity ({opacity: 1, top: "50% "})

/* After a delayof 1000 ms, slide the element out of view .*/

. Velocity ({opacity: 0, top: "-50%" },{ delay: 1000 });

In the above example, the second Velocity call knows that it should automatically start from opacity 1 and top 50%.

The browser itself can ultimately execute many of these same optimizations, but doing so will significantly reduce the way developers can make animated code. Therefore, for the same reason, because jQuery does not use RAF (as described above), the browser will not forcibly optimize it, or even give a small opportunity to break the specifications or deviate from expectations.

Finally, we can compare the two JavaScript animation libraries (Velocity. js and GSAP.

GSAP is the first animation library used to demonstrate the impressive animation performance of JavaScript DOM. It does, but has some disadvantages:

In medium-to high-load animations, the DOM interaction overhead of GSAP results in Frame loss during the animation start time and process.

On the contrary, Velocity. js is released under the ultra-loose MIT license, GSAP is closed-source, and annual licensing fee is required for many types of commercial use.

Because GSAP is a complete animation Kit, it is three times the size of Velocity. However, GSAP has such rich features that help it become the Swiss army knife for animation.

I recommend that you use GSAP when you need to precisely control timing (such as re-painting, pause/resume) and motion (such as the beiser curve path. These features are crucial in game development and some special applications, but they are usually not used in Web application UIS.

Velocity. js

Referencing the rich features of GSAP does not mean that Velocity itself is lightweight in terms of features. on the contrary, in the only 7 kb after compression, Velocity not only copies jQuery $. all functions of animate () include color animation, conversion, loop, easing effect, class animation, and scrolling.

In short, Velocity is the best combination of jQuery, jQuery UI, and CSS gradient effect.

In addition, from the perspective of convenience, Velocity uses jQuery's $. the queue () method, so that the $. animate (), $. fade (), and $. seamless interoperability of delay () functions. besides, because the syntax of Velocity is the same as that of $. the syntax of animate () is the same. You do not need to change any code on the page.

Let's take a quick look at Velocity. js. at the basic level, Velocity's behavior is the same as $. animate:

?

1

2

3

4

5

6

7

 

$ Element

. Delay (1000)

/* Use Velocity to animate the element's top property over a duration of 2000 ms .*/

. Velocity ({top: "50%"}, 2000)

/* Use a standard jQuery method to fade the element out once Velocity is done animating top .*/

. FadeOut (1000 );

At its most advanced level, you can create a complex rolling scenario with 3D animation-using almost two lines of simple code:

?

1

2

3

4

5

$ Element

/* Scroll the browser to the top of this element over a duration of 1000 ms .*/

. Velocity ("scroll", 1000)

/* Then rotate the element around its Y axis by 360 degrees .*/

. Velocity ({rotateY: "360deg"}, 1000 );

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.