How JavaScript works (JavaScript works) (13) CSS and JS animation underlying principles and how to optimize their performance

Source: Internet
Author: User

Personal Summary: It takes 20 minutes to finish reading this article.

This is the 13th chapter of how JavaScript works.

Overview

As you know, animations play a key role in creating compelling Web applications. As users become more focused on the user experience, merchants are beginning to realize the importance of a perfect, enjoyable user experience, resulting in more and more dynamic network applications and the ability to interact more dynamically. This requires the network application to provide more complex animation to achieve a smooth state transition throughout the user's use process. Now, this is commonplace. Users are becoming increasingly picky, and they subconsciously expect a user interface that is responsive and well-interactive.

However, animating the interface is not necessarily a simple matter. The timing of the animation, the aspects and the animation effects are very vague concepts.

JavaScript and CSS animations comparison

JavaScript and CSS are the two main ways to create Web page animations. Two kinds of trait, see the situation use it.

CSS Animations

Using CSS animations is the easiest way to move elements on the screen.

We'll start with a small example of how to move an element 50 pixels on the x and X coordinates. Moves the element through a CSS transition that lasts for 1 seconds.

.box {  -webkit-transform: translate(0, 0);  -webkit-transition: -webkit-transform 1000ms;  transform: translate(0, 0);  transition: transform 1000ms;}.box.move {  -webkit-transform: translate(50px, 50px);  transform: translate(50px, 50px);}

When adding a class to an element move , change transform the value and then develop a transition effect.

In addition to the transition duration, there are easing parameters, which are primarily responsible for the animation experience. This parameter is described in more detail later.

If you can create individual style classes to manipulate animations through the code snippets above, you can also use JavaScript to toggle each animation.

The following elements:

<div class="box">  Sample content.</div>

Then, use JavaScript to toggle each animation.

var boxElements = document.getElementsByClassName(‘box‘),    boxElementsLength = boxElements.length,    i;for (i = 0; i < boxElementsLength; i++) {  boxElements[i].classList.add(‘move‘);}

The code snippet above adds a box class for each element containing the class move to trigger the animation.

Doing so can provide a good balance for your Web application. You can focus on using JavaScript to manipulate the application state, then just set the appropriate class for the target element and let the browser handle the animation. If you choose to do so, you can listen to the elements of the transitionend event, in addition to dealing with the old version of IE browser compatibility issues.

The following listener transitioned event is triggered at the end of the animation.

var boxElement = document.querySelector(‘.box‘); // 获取第一个包含 box 类的元素boxElement.addEventListener(‘transitionend‘, onTransitionEnd, false);function onTransitionEnd() {  // Handle the transition finishing.}

In addition to using CSS transitions, you can also use CSS animations, which allow you to better control individual animation keyframes, duration, and number of cycles.

KeyFrames are used to inform the browser of the expected CSS property values at a specified point in time and then fill in the blanks.

Take a look at the following example:

/** * 该示例是没有包含浏览器前缀的精简版。加上以后会更加准确些。 * */.box {  /* 选择动画名称 */  animation-name: movingBox;  /* 动画时长 */  animation-duration: 2300ms;  /* 动画循环次数 */  animation-iteration-count: infinite;  /* 每次奇数次循环时反转动画 */  animation-direction: alternate;}@keyframes movingBox {  0% {    transform: translate(0, 0);    opacity: 0.4;  }  25% {    opacity: 0.9;  }  50% {    transform: translate(150px, 200px);    opacity: 0.2;  }  100% {    transform: translate(40px, 30px);    opacity: 0.8;  }}

effect Example-https://sessionstack.github.io/blog/demos/keyframes/

Use CSS animations to define the animation itself that is independent of the target element, and then set the element's Animation-name property to work with the desired animation effect.

CSS animations still need to be prefixed with the browser, adding prefixes in Safari, Safari mobile browser and Android side -webkit- . Chrome, Opera, Internet Explorer, and Firefox all don't need to be prefixed. There are a number of tools that you can use to create styles that contain any prefix, so you don't need to have style prefixes in your source files.

You can use Autoprefixer or cssnext to add a prefix to a style.

JavaScript Animations

Using JavaScript to create animations is more complicated than CSS transitions or css animations, but in general it provides powerful functionality for development.

In general, you can inline JavaScript animations as part of your code. They can also be encapsulated in other objects. The following is the JavaScript code to reproduce the CSS transitions described earlier:

var boxElement = document.querySelector(‘.box‘);var animation = boxElement.animate([  {transform: ‘translate(0)‘},  {transform: ‘translate(150px, 200px)‘}], 500);animation.addEventListener(‘finish‘, function() {  boxElement.style.transform = ‘translate(150px, 200px)‘;});

By default, Web page animations only modify the appearance of an element. If you want the element to stay where it was moved to, you have to modify its underlying style at the end of the animation. This is why, in the above example, you listen to the finish event and then set the box.style.transform property to translate(150px, 200px) the same reason that the property value is the same as the second style conversion that the CSS animation performs.

By using JavaScript animations, you have complete control over the style of each step element. This means that you can slow down, pause, stop, or flip an animation to manipulate the target element at will. Because animation behavior can be encapsulated appropriately, it is especially useful when building complex object-oriented applications.

Easing definition

Moving naturally and smoothly will give your Web application a better user interaction experience.

In natural conditions, no thing can move from one point to another in a straight line. In real life, objects in the physical world around us accelerate or decelerate as they move, because we don't live in a vacuum and have different factors that affect the state of things. The human brain is expected to feel this movement, so it is good for you to use this knowledge when animating Web applications.

This is the term that you should understand:

    • "Ease in"-start moving slowly and then accelerate
    • "Ease out"-start moving quickly and then slow down

You can combine two animations, such as "ease in out".

Easing can make animations more natural and smooth.

Easing keywords

You can select any of the easing methods for CSS transitions and animations. Different keywords can affect the easing of the animation. You can also fully customize the easing method.

Here are the CSS keywords that you can choose to control easing:

    • linear
    • ease-in
    • ease-out
    • ease-in-out

Let's take a closer look and see how they're performing.

Linear Animation

Animations that do not use any of the easing methods are linear.

The following is an illustration of the linear transition effect:

Values increase as time passes. Using linear animations will make the animation unnatural. In general, avoid the use of linear dynamic effects.

Use the following code to implement a simple linear animation:

transition: transform 500ms linear;

Ease-out Animation

As mentioned earlier, in contrast to linear, easing out lets the animation start quickly and slows down at the end. Here is the illustration:

In short, easing out is the most suitable interface experience, because the quick start will give people a quick response to the feeling of animation, and the end of the feeling is very smooth thanks to inconsistent movement speed.

To make a metaphor, such as those sports cars, the first startup speed is quite fast, which gives people a pleasant feeling. This is more in line with human perception of animation.

There are a number of ways to achieve ease out animation, and the simplest is the keyword in CSS ease-out .

transition: transform 500ms ease-out;

ease-in Animation

Contrary to ease-out animation-it starts slowly and then ends time-varying quickly. This is illustrated below:

and ease-out animation, because they start slowly to people to react to the feeling of lag, so ease-in make people feel animation unnatural. The animation ends with a strange feeling, because the whole animation is accelerating, and the real world slows down rather than accelerates when things suddenly stop moving.

Like Ease-out and linear animations, use CSS keywords to implement ease-in animations:

transition: transform 500ms ease-in;

Ease-in-out Animation

The animation is a collection of ease-in and Ease-out. This is illustrated below:

Do not set the animation duration too long, otherwise it will give a feeling that the interface does not respond.

Use ease-in-out CSS keywords to implement ease-in-out animations:

transition: transform 500ms ease-in-out;

Custom easing

You can customize your own easing curve, which allows you to control animations in your project more effectively.

In fact ease-in , linear and the ease keyword maps to a predefined Bezier curve, you can find more content about Bézier curves in CSS transitions specification and WEB animations specification.

Bezier curve

Let's look at how the Bezier curve works. A Bezier curve consists of four points, or, to be precise, two sets of values. Each pair of values contains the X and Y coordinates that represent the control points of the three Bezier curves. The starting coordinates of the Bezier curve are (0, 0) and the end coordinates are (1, 1). Two sets of numeric pairs can be set. The X-axis value of each control point must be between [0, 1], and the Y-axis value can exceed [0, 1], although the specification does not explicitly allow the value to be exceeded. Even a small difference in the X and Y values of each control point will output a completely different Bezier curve.

View Wikipedia's description of Bezier curves, in layman's words, now said that is the three times Bezier curve, the curve consists of four points, P0, P1, P2, P3 composition, then, P0 and P1 make up a pair, P2 and P3 constitute a pair, P1 and P2 is the control point, P0 and P3 is the beginning and Ends the node. As shown in the following:

Look at the Bezier graphs of two control nodes with similar but different coordinates.

And

As you can see, the two pictures are very different. The first control point vector difference is (0.045, 0.183), while the second control point vector difference is (-0.427,-0.054).

The style of the second curve is:

transition: transform 500ms cubic-bezier(0.465, 0.183, 0.153, 0.946);

The first set of values is the x and Y coordinates of the starting control point and the second set of values is the x and Y coordinates of the second control point.

Performance optimization

You have to maintain an animation frame number of 60 frames per second, otherwise it will affect the user experience.

Like everything else in the world, animations have a performance overhead. Some properties have a smaller animation performance overhead than other properties. For example, animating an width element height changes its geometry and may cause changes in the movement or size of other elements on the page. This process is called a layout. Layout and rendering are described in detail in the previous article.

In summary, you should try to avoid animating the properties that cause layout and drawing. For most modern browsers, the animation is limited to opacity and transform attributes.

Will-change

You can use Will-change to tell the browser that the properties of an element will change. This allows the browser to make the most appropriate optimizations in advance when changing the attributes of an element. But do not abuse will-change , because this will be counterproductive, so that the browser waste more resources, resulting in more performance problems.

Add the following code for transforms and opacity will-change :

.box {  will-change: transform, opacity;}

This property is very well compatible with Chrome, Firefox,opera.

How to choose JavaScript and CSS to perform animations

There is no solution to this problem. Just keep in mind the following principles:

    • CSS-based animations and native-supported web animations are typically handled by threads called "Synthetic threads." This differs from the main thread of the browser, where the main thread is used to perform computational styles, layouts, drawings, and JavaScript code. This means that if the browser runs a time-consuming task on the main thread, it will not disrupt the animation's operation.
    • Many times, the composition thread can also be used to process transforms and opacity change property values.
    • If any animations trigger drawing, layout, or both, the "main thread" will have to be processed. The fact is that the performance overhead of CSS and JavaScript-based animations and layouts, or drawing, will likely block all work related to CSS or JavaScript, making rendering a problem meaningless.
Use animations correctly

Good animations add a pleasant and interactive user experience to the project. You can use animations, regardless of width, debugging, positioning, color or background colors, but you must be aware of potential performance bottlenecks. Bad animation choices can affect the user experience, so animations must be efficient and appropriate. Minimize the use of animations. Use animations only to make the user experience smooth, natural rather than abusive.

Interacting with animations

Don't use animations just for the sake of use. Conversely, there is a strategic use of animations to enhance the user interaction experience. Avoid using unnecessary animations to interrupt or hinder the user's use.

Avoid animating properties with high performance overhead

Worse than bad animations are those that cause the page to lag. This type of animation makes users feel frustrated and unhappy.

Referencing resources
    • Https://developers.google.com/web/fundamentals/design-and-ux/animations/css-vs-javascript
    • https://developers.google.com/web/fundamentals/design-and-ux/animations/
    • Https://developers.google.com/web/fundamentals/design-and-ux/animations/animations-and-performance
Questions

You can look at this article on the web that describes the Bezier curve, so how can you use Bezier curves to make amazing animations?

How JavaScript works (JavaScript works) (13) CSS and JS animation underlying principles and how to optimize their performance

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.