Web Animations API
The Web Animations API (WAAPI) provides a common language for browsers and developers to describe animations on DOM elements. It unifies the declarative nature of CSS animations with the dynamic capabilities of JavaScript.
1. The Concept
WAAPI allows you to create animations that run on the browser's compositor thread (like CSS animations), ensuring smooth performance, while giving you full control via JavaScript to play, pause, reverse, or seek through the animation.
2. Basic Usage: element.animate()
The simplest way to use WAAPI is the animate() method on a DOM element. It takes two arguments: keyframes and options.
const box = document.querySelector('.box');
const animation = box.animate(
[
// Keyframes
{ transform: 'translateX(0px)', opacity: 1 },
{ transform: 'translateX(300px)', opacity: 0.5 }
],
{
// Timing options
duration: 1000,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out'
}
);
3. Keyframes
Keyframes are an array of objects. Each object represents a keyframe.
- Properties are camelCased (e.g.,
backgroundColorinstead ofbackground-color). - Offsets are optional (0 to 1). If omitted, they are distributed evenly.
const keyframes = [
{ opacity: 0, offset: 0 },
{ opacity: 1, offset: 0.5 },
{ opacity: 0, offset: 1 }
];
4. Controlling Animations
The animate() method returns an Animation object, which provides methods to control playback.
const animation = box.animate(keyframes, 2000);
// Pause
animation.pause();
// Play
animation.play();
// Reverse
animation.reverse();
// Speed up
animation.playbackRate = 2; // 2x speed
// Seek to a specific time
animation.currentTime = 500; // Jump to 500ms
// Finish immediately
animation.finish();
// Cancel (removes effects)
animation.cancel();
5. Promises and Events
The Animation object has a finished property which is a Promise that resolves when the animation completes.
animation.finished.then(() => {
console.log('Animation completed!');
});
6. WAAPI vs. CSS Animations
| Feature | CSS Animations | Web Animations API |
|---|---|---|
| Definition | Declarative (CSS) | Imperative (JS) |
| Control | Limited (Play/Pause via class toggling) | Full (Seek, Reverse, Speed) |
| Dynamic Values | Hard (requires CSS variables) | Easy (JS variables) |
| Performance | High (Compositor thread) | High (Compositor thread) |
programming/javascript/vanilla/javascript programming/javascript/vanilla/dom-manipulation programming/javascript/vanilla/promises-async-await