Web Animations API Tutorial Part 3: Multiple Animations

This is Part 3 of an introductory/tutorial series on the Web Animations API coming to browsers. I've updated the series content in June 2016, as Chrome and Firefox have both rolled out major updates (and some small spec changes). If you have thoughts/questions or see that I’ve misinterpreted the spec, please reach out to me on Twitter, @dancwilson.

After our discussion on the Animation’s controls and timelines within the Web Animations API, let’s talk about multiple animations.

Multiple Animations Per Element

See the Pen Multiple animate calls by Dan Wilson (@danwilson) on CodePen.

In this example, each rectangle has three animations applied (affecting transform, opacity, and color). You can call animate() on an element multiple times, similar to CSS allowing multiple animations.

With CSS:

#toAnimate {
  animation: pulse 1s, activate 3000ms, have-fun-with-it 2.5s;
}
@keyframes pulse { /* ... */ }
@keyframes activate { /* ... */ }
@keyframes have-fun-with-it { /* ... */ }

With the Web Animations API:

var animated = document.getElementById('toAnimate');
var pulseKeyframes, //defined the keyframes here.
    activateKeyframes,
    haveFunKeyframes;
var pulse = animated.animate(pulseKeyframes, 1000); //the second parameter as a number is a valid shorthand for duration
var activate = animated.animate(activateKeyframes, 3000);
var haveFunWithIt = animated.animate(haveFunKeyframes, 2500);

With the Web Animations API, this creates three Animation objects that can each be paused, played, finished, canceled, and manipulated via timeline or playback rate.

Get the Animations, Get Them All

So you’ve got an animation kicked off and playing, but you didn’t capture the Animation reference when you called animate() on the element. What’s a person to do?

See the Pen PqgKVK by Dan Wilson (@danwilson) on CodePen.

The spec allows for a method getAnimations() on the document. In the latest version of the spec it is directly on the document (document.getAnimations()) which is how it is implemented in Firefox 48+. However, as of Chrome 52 and the polyfill (as of v2.2.0), it is implemented according to the old spec which placed it on the new timeline object on the document.

//If including the polyfill you can use the following
var animations = document.getAnimations ? document.getAnimations() : document.timeline.getAnimations();
//returns array of all active (not finished and not canceled) animations

In the CodePen example, you will see several dots moving with random durations, delays, and transforms with an infinite duration. The ‘Pause All’ button calls getAnimations() and iterates through all the returned players (one for each animation) and pauses each one.

Next Time…

In the next part, we’ll look at the different ways a WAAPI animation can be created (because there’s more to it than just element.animate). Hint: document.timeline will make more appearances.

Check out the rest of this series: