The Web Animations API lets us construct animations and control their playback with JavaScript. This article will start you off in the right direction with fun demos and tutorials featuring Alice in Wonderland.

Meet the Web Animations API

The Web Animations API opens the browser’s animation engine to developers and manipulation by JavaScript. This API was designed to underlie implementations of both CSS Animations and CSS Transitions, and leaves the door open to future animation effects. It is one of the most performant ways to animate on the Web where supported, letting the browser make its own internal optimizations without hacks, coercion, or Window.requestAnimationFrame().

With the Web Animations API, we can move interactive animations from stylesheets to JavaScript, separating presentation from behavior. We no longer need to rely on DOM-heavy techniques such as writing CSS properties and scoping classes onto elements to control playback direction. And unlike pure, declarative CSS, JavaScript also lets us dynamically set values from properties to durations. For building custom animation libraries and creating interactive animations, the Web Animations API might be the perfect tool for the job. Let's see what it can do!

Browser Support

The basic Web Animations API features discussed in this article are available by default in Firefox 48+ and Chrome 36+. Webkit and Edge have moved the API onto their respective to-do lists, but until we see full support across all browsers, there’s a handy maintained polyfill that tests for feature support and adds it where necessary.

Writing CSS Animations with the Web Animations API

One of the more familiar ways to approach learning the Web Animations API is to start with something most web developers have played with before: CSS Animations. CSS Animations have a familiar syntax that breaks down nicely for demonstration purposes.

The CSS version

Here’s a tumbling animation written in CSS showing Alice falling down the rabbit hole that leads to Wonderland (see the full code on Codepen):

Notice that the background moves, Alice spins, and her color changes at an offset from her spinning. We’re going to focus on just Alice for this tutorial. Here’s the simplified CSS that controls Alice’s animation:

This changes Alice’s color and her transform’s rotation over 3 seconds at a constant (linear) rate and loops infinitely. In the @keyframes block we can see that 30% of the way through each loop (about .9 seconds in), Alice’s color changes from black to a deep burgundy then back again by the end of the loop.

Moving it to JavaScript

Now let’s try creating the same animation with the Web Animations API.

Here we’re using an array containing multiple objects. Each object represents a key from the original CSS. However, unlike CSS, the Web Animations API doesn’t need to explicitly be told the percentages along the animation for each key to appear at. It will automatically divide the animation into equal parts based on the number of keys you give it. This means that a Keyframe Object with three keys will play the middle key 50% of the way through each loop of the animation unless told otherwise.

When we want to explicitly set a key’s offset from the other keys, we can specify an offset directly in the object, separated from the declaration with a comma. In the above example, to make sure that Alice’s color changes at 30% (not 50%) for the color change, we are giving it offset: 0.3.

There must be at least two keyframes specified (representing the starting and ending states of the animation sequence). If your keyframe list has only one entry, Element.animate() will throw a NotSupportedError exception.

So to recap, the keys are equally spaced by default unless you specify an offset on a key. Handy, no?

The other thing you’ll notice is that it’s iterations, not iteration-count.

There are a number of small differences between the terminology used in CSS Animations and the terminology used in Web Animations. For instance, Web Animations doesn't use the string "infinite", but instead uses the JavaScript keyword Infinity. And instead of timing-function we use easing. We aren’t listing an easing value here because, unlike CSS Animations where the default animation-timing-function is ease, in the Web Animations API the default easing is linear — which is what we want here.

The animate() method can be called on any DOM element that could be animated with CSS. And it can be written in several ways. Instead of making objects for keyframes and timing properties, we could just pass their values in directly, like so:

While we can write CSS Animations with the Web Animations API, where the API really comes in handy is manipulating the animation’s playback. The Web Animations API provides several useful methods for controlling playback. Let’s take a look at pausing and playing animations in the Growing/Shrinking Alice game (check out the full code on Codepen):

In this game, Alice has an animation that causes her to go from small to big which we control via a bottle and a cupcake. Both of these have their own animations.

Pausing and playing animations

We’ll talk more about Alice’s animation later, but for now, let’s look closer at the cupcake’s animation:

The Element.animate() method will immediately run after it is called. To prevent the cake from eating itself up before the user has had the chance to click on it, we call Animation.pause() on it immediately after it is defined, like so:

Let’s take a look at playbackRate first — a negative playbackRate will cause an animation to run in reverse. When Alice drinks from the bottle, she grows smaller. This is because the bottle changes her animation’s playbackRate from 1 to -1:

In Through the Looking-Glass, Alice travels to a world where she must run to stay in place — and run twice as fast to move forward! In the Red Queen’s Race example, Alice and the Red Queen are running to stay in place (check out the full code on Codepen):

Because small children tire out easily, unlike automaton chess pieces, Alice is constantly slowing down. We've done this in the code by setting a decay on her animation’s playbackRate:

The background elements also have playbackRates that are impacted when you click or tap. What happens when you make Alice and the Red Queen run twice as fast? What happens when you let them slow down?

Getting information out of animations

Imagine other ways we could use playbackRate, such as improving accessibility for users with vestibular disorders by letting them slow down animations across an entire site. That’s impossible to do with CSS without recalculating durations in every CSS rule, but with the Web Animations API, we could use the upcoming (not supported in browsers yet!) document.getAnimations() method to loop over each animation on the page and halve their playbackRates, like so:

With the Web Animations API, all you need to change is just one little property!

Another thing that’s tough to do with CSS Animations alone is creating dependencies on values provided by other animations. For instance, in the Growing and Shrinking Alice game example, you might have noticed something odd about the cake’s duration:

duration: aliceChange.effect.timing.duration / 2

To understand what’s happening here, let’s take a look at Alice’s animation:

Alice’s animation has her going from half her size to twice her size over 8 seconds. Then we pause her:

aliceChange.pause();

If we had left her paused at the beginning of her animation, she’d start at half her full size, as if she’d drunk the entire bottle already! We want to set her animation’s “playhead” in the middle, so she’s already halfway done. We could do that by setting her Animation.currentTime to 4 seconds, like so:

aliceChange.currentTime = 4000;

But while working on this animation, we might change Alice’s duration a lot. Wouldn’t it be better if we set her currentTime dynamically, so we don’t have to make two updates at a time? We can, in fact, do so by referencing aliceChange’s Animation.effect property, which returns an object containing all the details of the effect(s) active on Alice:

aliceChange.currentTime = aliceChange.effect.timing.duration / 2;

effect lets us access the animation’s keyframe and timing objects — aliceChange.effect.timing points to Alice’s timing object (which is of type AnimationEffectTimingReadOnly) — this contains her AnimationEffectTimingReadOnly.duration. We can divide her duration in half to get the midpoint for her animation’s timeline, setting her to be normal height. Now we can reverse and play her animation in either direction to make her grow smaller or larger!

And we can do the same thing when setting the cake and bottle durations:

Now all three animations are linked to just one duration, which we can change easily from one place.

We can also use the Web Animations API to figure out the animation's current time. The game ends when you run out of cake to eat or empty the bottle. Which vignette players are presented with depends on how far along Alice was in her animation, whether she grew too big and can't get in the tiny door anymore or too small and cannot reach the key to open the door. We can figure out whether she's on the large end or small end of her animation by getting her animation's currentTime and dividing it by her activeDuration:

Prefer promises? The Web Animations API also specifies two promises: onfinish and oncancel.

These promises are not fully supported as of this writing.

Conclusion

These are the basic features of the Web Animations API, most of which are already supported across the latest release versions of Firefox and Chrome. By now you should be ready to "jump down the rabbit hole" of animating in the browser and ready to write your own animation experiments! If you're using the API and want to share, try using the #WAAPI hashtag. We will be watching and will write more tutorials to cover further features as support spreads!