For other translations of this series, see [JS Working Mechanism – Xiaobai’s 1991 column – Nuggets (juejin. Cn)] (juejin.cn/column/6988… “Juejin. Cn/column / 6988… > < span style = “max-width: 100%; clear: both; If your product is interactive, learn about it.

An overview of the

Animation has come to play an important role in building web applications. Users’ attention is shifting to UX, and businesses are increasingly recognizing the value of a pleasurable user experience. So web applications are getting heavier and more dynamic. Users now naturally expect websites to be interactive and responsive.

But animation is not that simple. The timing of the animation, the object, and the effect are all vague.

JS vs CSS animation

The two main ways to animate are using CSS and JS. There is no right or wrong way to choose a solution, just what effect you want to achieve

CSS animations

CSS animations are the easiest way to get things moving on the screen. Let’s look at an example of how to move an element 50px along both the X and Y axes. This example was done using CSS movement and cost 1000ms.

.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);
}
Copy the code

Add the move class, transform values change, and start moving.

In addition to the time of transition, there is also an option to slow down, showing the animation feel. We’ll discuss more details later. Create a separate CSS class as above to manage the animation, and then the user can use JS to toggle the following elements of the animation on/off

<div class="box">
  Sample content.
</div>
Copy the code

Toggle animation with JS:

var boxElements = document.getElementsByClassName('box'),
    boxElementsLength = boxElements.length,
    i;

for (i = 0; i < boxElementsLength; i++) {
  boxElements[i].classList.add('move');
}
Copy the code

Trigger animation by adding a Move class to all box class elements.

In doing so, you can use JS to manage state, then set the appropriate style classes for the target element, and then hand the animation over to the browser. If you do this, you can also listen for transitionEnd events (in addition to compatibility with older VERSIONS of IE)

A transitioned event will trigger at the end of the animation, like this

var boxElement = document.querySelector('.box'); // Get the first element which has the box class.
boxElement.addEventListener('transitionend', onTransitionEnd, false);

function onTransitionEnd() {
  // Handle the transition finishing.
}
Copy the code

In addition to using CSS transitions, you can also use post-CSS animations, which allow you to control each individual keyframe, time, and number of loops.

Keyframes are used to inform the browser of the CSS properties at a specified point in time, and then fill in the blanks

Here’s an example:

/** * This is a simplified version without * vendor prefixes. With them included * (which you will need), things get far * more verbose! */ .box { /* Choose the animation */ animation-name: movingBox; /* The animation's duration */ animation-duration: 2300ms; /* The number of times we want the animation to run */ animation-iteration-count: infinite; /* Causes the animation to reverse on every odd iteration */ animation-direction: alternate; } @keyframes movingBox { 0% { transform: translate(0, 0); Opacity: 0.4; Opacity: 0; opacity: 0; } 50% { transform: translate(150px, 200px); Opacity: 0.2; } 100% { transform: translate(40px, 30px); Opacity: 0.8; }}Copy the code

Looks like this (quick demo) – sessionstack. Making. IO/blog/demos /…

With CSS animation, you can define the animation itself (independent of the element) and then use the animation property name to select the desired animation effect.

CSS animations still have some vendor prefixes, such as -webkit- on Safari, Safari Mobile, and Android. Chrome, Opera, Internet Explorer, and Firefox don’t use prefixes. There are many tools that can help you create the version of CSS prefixes you need so you don’t have to write prefixes in your code.

JavaScript animation

Using JS animations is much more complex than CSS transitions and animations, but gives the developer much more control.

JS animations need to be written in code as part of your code. You can encapsulate them into other objects. Here is the JavaScript code to reproduce the CSS transition 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)';
});
Copy the code

By default, web animation only modifies the presentation of an element. If you want to keep your object in its target position, you can modify its underlying style after the animation is over. That’s why we listen for the Finish event and set the box.style.transform property to translate(150px, 200px), which is the same value as the second style transformation performed by the CSS animation.

With JS animations, you have complete control over the style of elements at every step. You can slow down animation, pause, stop, flip, manipulate. When you build complex, object-oriented applications, because you can encapsulate them properly.

What is slow motion

Natural and smooth movement makes web applications have a better user interaction experience.

Nothing is linear from one point to another. In fact, in the real world things move faster or faster. The human brain is familiar with such object motion, so it is better to use this knowledge when using animation in applications.

To understand some concepts:

  • “Ease in” – Start moving slowly and then speed up
  • “Ease out” – Start moving quickly and then slow down

The two can be combined to “ease in and out”. This will make your animation look more natural.

Ease the keyword

CSS transitions and easing allows you to choose the type you want, and there are a few different keywords that affect the easing effect of the animation. You can also customize some easing effects.

Commonly used slow keywords are these:

  • linear(linear)
  • ease-in(slow)
  • ease-out(slow)
  • ease-in-out(Slow access)

Look at what they actually do

Linear

Linear means there is no easing effect

The transition looks like this

Linear effects are uniform, which makes the effect seem unreal. So avoid it

A simple example to implement it: Transition: Transform 500ms Linear;

Ease-out

The animation starts quickly and slows down at the end. The transition looks like this

Caching is best in the UI because it starts quickly and feels responsive. And the finish feels smooth thanks to the inconsistent speed of movement.

There are many ways to achieve this effect, the simplest being to use ease-out in CSS

transition: transform 500ms ease-out;
Copy the code

Ease-in

The effect of slowing in is the opposite of slowing out – it starts slowly and ends quickly. The transition looks like this:

Easing in is very counterintuitive compared to easing out. It starts slowly and feels slow to respond. It ended quickly, which felt strange because the whole animation was speeding up, whereas in the real world things slow down when they suddenly stop moving instead of speeding up. Similar to easing out, you can use CSS keywords

transition: transform 500ms ease-in;
Copy the code

Ease-in-out

This animation combines easing in and easing out, and its animation looks like this

Don’t let the action last too long and it will feel like your UI is unresponsive. This can also be done using CSS keywords:

transition: transform 500ms ease-in-out;
Copy the code

Customize the easing effect

You can customize your easing curves to give you more control over the animations in your project.

In fact, ease-in, Linear, and ease keywords map to predefined Bessel curves, Find out more about Bessel curves in the CSS Transitions Specification and Web Animations Specification.

Bessel curve

Let’s see how bezier curves work. There are two pairs of Bezier curves. Each pair of values contains X and Y coordinates representing the control points of the cubic Bezier curve. The bezier curve starts at (0, 0) and ends to the left at (1, 1). You can set the value of each pair, and the X-axis value of each control point must be between [0, 1], while the Y-axis value can exceed [0, 1], although the specification does not explicitly allow more than that. Look at wikipedia for a Bessel curve, which is, in general terms, what’s now called a cubic Bessel curve, and it consists of four points, P0, P1, P2, P3, so P0 and P1 are a pair, P2 and P3 are a pair, P1 and P2 are the control points, P0 and P3 are the start and end nodes. As shown below:

A small difference between X and Y can make a big difference. Look at two Bessel graphs with similar but different coordinates of control nodes.

and

These two graphs are very different, but very different. The vector difference of the first control point is (0.045, 0.183), while the vector difference of the second control point is (-0.427, -0.054).

The CSS for the second line looks like this:

Transition: Transform 500ms Cubic - Bezier (0.465, 0.183, 0.153, 0.946);Copy the code

The first set of values is the X and Y coordinates of the initial control point and the second set of values is the X and Y coordinates of the second control point.

Performance optimization

When using animation, you need to maintain 60fps at all times; otherwise, user experience will be affected.

But animation isn’t free. Some properties have a lower animation performance overhead. However, animating the width and height of an element changes its geometry and may cause other elements on the page to move or change their size. This process is called layout. We discussed this in Chapter 11.

In general, you should avoid animating properties that cause layout and drawing. Most modern browsers restrict animations to the opacity and transform properties.

Will-change

You can use will-change to tell the browser that you will be changing element attributes, which allows the browser to start selecting the appropriate optimization strategy ahead of time. Do not overuse will-change, however, as it can cause the browser to waste resources and ultimately affect performance.

Add the will-change code for transforms and opacity as follows:

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

Take a look at browser support

Choose between JS and CSS

Choosing JS and CSS is not a matter of right or wrong, it can be anyone. When choosing, you can follow these principles:

  • Css-based animations, Web animations that are natively supported, tend to be handled by “synthetic threads”This thread is different from the main thread, which handles styling, layout, drawing, and JS execution. This means that these animations can continue to run without interruption if the browser is doing heavy work in the main thread.
  • In many cases, it can also be handled by synthetic threadstransforms 和 opacityProperty value changes.
  • If a drawing or layout is triggered, the main thread is required to handle it. In both CSS-BASED and JS-BASED animation, the overhead of drawing and layout can block CSS and JS execution.

Choose the appropriate animation

Good animation adds an enjoyable and interactive user experience to the project. You can use any animation you like, be it width, debugging, positioning, color, or background color, but be aware of potential performance bottlenecks. Poor animation choices can affect the user experience, so animations must be efficient and appropriate. Use animations as little as possible. Use only animation to make the user experience smooth and natural, not overuse.

Use animations to support interaction

Don’t use animations just because you can. Instead, use animation strategically to enhance the user interaction experience. Don’t use animations to interrupt or block user behavior unless necessary.

Reject expensive animation properties

The only thing worse than animation is bad placement and resulting in page blocks. This animation makes the user feel more uncomfortable.