Creating cool animation with web animations API

Time:2020-3-25

How to write animation gracefully with native JS? I believe waapi can help you.

Creating cool animation with web animations API

Web Animations API

The web animations API (waapi) allows us to write and control animations in JavaScript.
These APIs are designed to interface with CSS animations and CSS transitions. In the future, these APIs will be supplemented to make them more powerful. It is one of the most effective ways to support animation on the network.

With the web animation API, we can move interactive animation from style sheets to JavaScript, separating performance from behavior. We no longer need to rely on DOM, such as writing CSS properties and scope classes to elements to control the direction of playback. Unlike pure declarative CSS, JavaScript also allows us to dynamically set property values to duration. For building custom animation libraries and creating interactive animations, the web animation API may be the perfect tool to do the job.

A simple example: waapi implementation of carousel chart

Compare with other animation methods

When we talk about web page animation, we naturally associate with CSS3 animation, JS animation, SVG animation, apng animation and other technologies, as well as jQuery. Animation () and other animation packaging libraries, and choose different implementation methods according to the actual animation content design.

However, every current animation technology has some disadvantages, for example, CSS3 animation must obtain the dynamic change value through JS, the time of setinterval is often imprecise and it will jam, apng animation will bring a big file volume problem, and the introduction of additional animation packaging library is not suitable for performance sensitive business. At present, for developers, it seems that they can’t have both. They want to get more powerful and convenient animation control ability, and they want to have enough fluency and elegance in performance and experience. If there is a general animation solution supported by browser natively, it will be excellent.

W3C puts forward web animation API (waapi for short) because of this. It is dedicated to the collection of CSS3 animation performance, JavaScript flexibility, rich animation library and other advantages. It will control as much animation as possible by the native browser, and add many variables, controls and or tuning options that CSS does not have.

Browser support

Support for waapi features is available in Firefox 48 + and chrome 36 +. WebKit and edge have moved the waapi to their respective to-do lists. You can view the full browser support on can I use

Waapi has a comprehensive and powerful external library of Polyfill, which enables us to use it in production environment now, even when the browser is limited. Web-animations.min.js enables waapi to run in most browsers.

Waapi core usage

element.animate( keyframes, AnimationEffectTimingProperties ); 

Keyframes: an array of keyframe objects
Animationeffecttimingproperties: objects for animation effects properties

E.g.

document.getElementById("elementId").animate(
    [
        { transform: 'rotate(0)', color: '#000' },
        { transform: 'rotate(360deg)', color: '#fff' }
    ], 
    {
        duration: 3000,
        iterations: Infinity
    }
);

The basic syntax of the waapi is very similar to jQuery’s. Animate(). However, wwapi is supported by browser natively. It does not need to introduce external libraries, and has great advantages in performance. Next, we learn the usage of waapi step by step.

Array of keyframe objects

Using waapi, the first thing to do is to create a keyframe object array similar to CSS3 @ keyframes.

E. G. create an array of key frame objects for the slide animation of the carousel

var slidingLeft = [
    //Simple sliding through the gradients of margin left and opacity
    { marginLeft: '0px', opacity: 1 },
    { opacity: 0.6, offset: 0.7 },
    { marginLeft: "-5rem", opacity: 1 }
];

The difference between web animation API and CSS3 Animation:

  • Waapi doesn’t need to explicitly tell the percentage of every keyframe in the animation when it appears, it will automatically divide the animation into equal parts according to the number of keyframes you give. When we want to explicitly set the offset between one key and other keys, we can directly specify an offset in the object (offset: the size range is 0 ~ 1).
  • In waapi key frame objects, hump writing method of element attributes is needed, for example, the attribute “margin left” corresponding to CSS and “margin left” corresponding to waapi key frame objects.
  • The waapi must specify at least two keyframes representing the start and end states of the animation sequence. If your keyframe object array has only one object member, element. Animate() will throw an unsupported exception.

Objects for animation effects attributes

We also need to create an animation effect timing properties object.
E.g.

var animateOptions = {
    duration: 1500,
    easing: 'ease-in-out',
}

It should be noted that animationeffecttimingproperties has some technical terms that are different from the familiar CSS3 animation properties.
The following table shows the corresponding relationship between them.

AnimationEffectTimingProperties CSS3 animation property Sketch
duration animation-duration Specifies the seconds or milliseconds that an animation takes to complete a cycle. The default is 0.
easing animation-timing-function Specifies the speed curve of the animation.
delay animation-delay Specifies when the animation starts. The default is 0.
iterations animation-iteration-count Specifies the number of times the animation is played. The default is 1.
direction animation-direction Specifies whether the animation plays backwards in the next cycle. The default is’ normal ‘.
fill animation-fill-mode Specifies whether animation effects are visible before or after playback.
endDelay No corresponding attribute Specifies the delay time after the end of the animation.
iterationStart No corresponding attribute Specifies the start time of the animation during the iteration.
  • The default value of easing is linear, while the default value of animation timing function is ease. Use appropriate easing when using waapi to avoid making animation mechanical and tedious (the default linear means that the speed of animation is the same from beginning to end).
  • Corresponding to the animation iteration count is iterations. If you want to keep the animation going, use infinity instead of infinity. Note that infinity doesn’t need to be wrapped in commas, it’s a JavaScript keyword, and the other values are strings.
  • The time unit uses MS instead of S, which is more acceptable for developers who have written JavaScript. (in fact, MS can also be used in CSS animation, but no one can use it like this. )
  • Enddelay indicates the delay time after the end of the animation, and the default value of delay is 0. If you want to string multiple animations together, but want a time interval between the end of an animation and the beginning of any subsequent animation, you can use enddlay.
  • Iteration start represents the start time of the animation during the iteration. E. G. if iterations is set to 1 and iterationstart is set to 0.5, the animation will play from the middle to the end of the animation, then from the beginning to the middle of the animation. If you set both iterations and iterations start to 0.5, the animation will play from the middle to the end.

After creating the “array of keyframe objects” and “objects of animation effect attributes”, you can simply start an animation. You can see specific examples later in the article.

element.animate( slidingLeft, animateOptions );

If we want to learn how to control the animation created with waapi, we still need to understand the animation object.

Animation object

The animate method doesn’t just let elements use animation, it also has its own return value, an animation object. By changing the properties of the object and calling its methods, you can control the animation gracefully.

var animationObj = element.animate(keyframes, AnimationEffectTimingProperties );

The animation object has the following properties:

Attribute name Significance
currentTime The current time value of the animation, in milliseconds. If the timeline is missing, its value is null, which means the animation is not active or has not been played.
effect The target effect of the animation. Can be an effect object of type based on animationeffectreadonly, such as keyframeeffect or null.
finished Read-only. Returns the promise object executed after this animation completes.
id A string identifying the animation.
playState Read-only. The playing state of animation usually includes running, paused and finished.
playbackRate The playback speed of the animation. The default value is 1. When the value is 0.5, the animation slows down by half, and when the value is negative, the animation plays back
ready Read-only. Returns the promise object executed when the current animation is ready to play.
startTime The scheduled time at which animation playback begins. The default is null. You can change this value so that the animation starts at a different time.
timeline The timeline associated with the current animation. The default is the same as the document’s timeline.

The animation object has methods:

Method name purpose
cancel() Clears all keyframe effects caused by this animation and stops its playback.
finish() Sets the current playback time to the animation end time corresponding to the current playback direction. If it is normal playback, set the current playback time to the total animation time; if it is reverse playback, set the current playback time to 0.
pause() Pause animation
play() Start or continue playing the animation. If the animation is complete, play the animation again.
reverse() Reverses the playback direction of the animation. If called on an unplayd animation, the animation plays back from the end to the beginning. If you call a paused animation, it continues to play in the opposite direction. The same effect can be achieved by setting playbackrate * = – 1

Event handler for animation object (callback function):

Wwapi supports event and promise to handle events.
Here are two types of events:

  • OnCancel: defines the callback function that is triggered when the animation is cancelled or when cancel() is executed.
  • Onfinish: defines the callback function triggered when the animation finishes playing naturally or when finish() is executed.

E. G. if an animation is cancelled, remove its elements.

    animation.oncancel = animation.effect.target.remove();

Promise
The promise object is used to represent the final completion (or failure) of an asynchronous operation and its result value.
The ready and finished properties of the animation object return a promise object, which corresponds to the time when the animation is ready to play and the end of play, respectively. Here is an example of using promise to handle event callbacks:

myAnimation.finished.then(() =>
 element.remove())

The document. Getanimations () method returns an array of all currently valid animation objects, including CSS animation, CSS transition, and web animation.
In the console drawer of the developer tool (F12) of the newer version of Chrome browser, you can also view all animations in the page, including those defined with CSS3:
Creating cool animation with web animations API

Waapi example – carousel chart

After understanding the above knowledge, we can use wwapi to implement a simple rotation chart, click to open codepen preview and view the complete code.
JS part code:

var indexBody = document.querySelector(".index_body");
var btnLeft = document.querySelector(".left_btn");
var btnRight = document.querySelector(".right_btn");
var slideBox = document.querySelector('.slidebox');
var items = slideBox.getElementsByClassName("slide_item");

//Using web animations to create animation, left and right slides share one animation
var slidingLeft = [
    {marginLeft: '0px', opacity: 1},
    {opacity: 0.6, offset: 0.7},
    {marginLeft: "-5rem", opacity: 1}
];

var sliding = slideBox.animate(
    slidingLeft,
    {
        duration: 1500,
        easing: 'ease-in-out',
    }
);

sliding.onfinish = function(){
    slideBox.style.marginLeft = '0px';
    if(sliding.playbackRate != -1){
        slideBox.appendChild(items[0]);
    }
    btnRight.onclick = slideRight;
    btnLeft.onclick = slideLeft;
};

function slideRight(){
    Sliding.playbackrate = 1; // switch the sliding direction to right
    sliding.play();
    btnLeft.onclick = null;
    btnRight.onclick = null;
    // console.log(sliding.effect);
};

function slideLeft(){
    slideBox.insertBefore(items[items.length - 1],items[0]);
    slideBox.style.marginLeft = '-5rem';
    Sliding.playbackrate = - 1; // switch the sliding direction to the left
    sliding.play();
    btnLeft.onclick = null;
    btnRight.onclick = null;
};

btnRight.onclick = slideRight;
btnLeft.onclick = slideLeft;

//Auto slide
var slideTimer = setInterval(() => {
    btnRight.click();
},3000);

//Stop sliding on mouse over
indexBody.onmouseover = function(){
    clearInterval(slideTimer);
};

//Continue to slide automatically when the mouse leaves
indexBody.onmouseout = function(){
    slideTimer = setInterval(() => {
        btnRight.click();
    },3000);
};

The official demo of Web animations is very suitable for students who are new to waapi as a starting example.
In addition, animista, a cool animation library, is recommended. There are many animations implemented with CSS3 (code can be viewed online, mainly keyframes). We can try to achieve the same animation effect with wwapi.

Reference material

  • Using the web animations API website: MDN
  • Fan Hongchun, translator of CSS animation and web animation API
  • “Web animation API from entry to first place” by alloyteam
  • Animation website: MDN
  • CSS3 animation properties website: w3school