In a nutshell, the Web Animations API (WAAPI) enables you to implement CSS3-style animations using JavaScript code directly.
While CSS3 animations excel at simple and reusable static animations, WAAPI binds controls and parameters directly to individual DOM elements in JavaScript. This makes WAAPI ideal for dynamic, reactive, runtime-calculated, or randomized animations with programmatic playback control.
The basic syntax is element.animate(keyframes, options). In its simplest form, options can be a single duration number (in milliseconds). Unlike CSS3 animations which default to ease, Web Animations API defaults to linear timing when duration alone is specified.
const simpleFadeBox = document.getElementById('simpleFadeBox');
// 3000ms fade-in with default linear timing
const fadeAnimation = simpleFadeBox.animate([
{ opacity: 0 },
{ opacity: 1 }
], 3000);
Detailed options are passed as an object matching CSS3 animation-* properties. The offset property corresponds to CSS @keyframes percentages (e.g. offset: 0.4 is 40%). Notice the red circle appears rapidly in the first 40% of the timeline and fades over the remaining 60%, stepping through discrete frames with steps(8, end) and looping with iterations: Infinity.
const circleElement = document.getElementById('steppedRedCircle');
const steppedAnimation = circleElement.animate([
{ opacity: 0 },
{ opacity: 1, offset: 0.4 }, // 40% progress mark in CSS
{ opacity: 0 }
], {
duration: 3000,
delay: 0,
fill: 'forwards',
easing: 'steps(8, end)',
iterations: Infinity // Note uppercase 'Infinity' in JS vs CSS 'infinite'
});
The Animation object returned by element.animate() provides imperative playback methods: play(), pause(), reverse(), finish(), and cancel().
const controlBox = document.getElementById('controlMotionBox');
const myAnimation = controlBox.animate([
{ transform: 'translateX(0px) rotate(0deg)', backgroundColor: '#3b82f6' },
{ transform: 'translateX(240px) rotate(180deg)', backgroundColor: '#ec4899' }
], {
duration: 2500,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out'
});
// Interactive controls
btnPlay.onclick = () => myAnimation.play();
btnPause.onclick = () => myAnimation.pause();
btnReverse.onclick = () => myAnimation.reverse();
btnFinish.onclick = () => myAnimation.finish();
btnCancel.onclick = () => myAnimation.cancel();
updatePlaybackRate()
updatePlaybackRate() sets the animation speed after synchronizing playback positions. Unlike directly setting the playbackRate property, updatePlaybackRate() prevents sudden visual jumps/stutters when changing velocity or reversing direction mid-flight.
const spinner = document.getElementById('speedSpinner');
const rotateAnim = spinner.animate([
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(360deg)' }
], {
duration: 2000,
iterations: Infinity,
easing: 'linear'
});
function setSpeed(rate) {
if (typeof rotateAnim.updatePlaybackRate === 'function') {
rotateAnim.updatePlaybackRate(rate);
} else {
rotateAnim.playbackRate = rate;
}
}
onfinish, oncancel, finished)
Web Animations API provides callback events (onfinish, oncancel) and Promise interfaces (animation.finished, animation.ready). Promises resolve cleanly when the animation reaches completion, making async sequencing straightforward.
const target = document.getElementById('eventTarget');
let anim = null;
function runAnimation() {
anim = target.animate([
{ transform: 'scale(1) translateY(0)', opacity: 1 },
{ transform: 'scale(1.25) translateY(-25px)', opacity: 0.2 }
], {
duration: 1800,
fill: 'forwards',
easing: 'ease-out'
});
// Event callbacks
anim.onfinish = () => log('Event: onfinish triggered');
anim.oncancel = () => log('Event: oncancel triggered');
// Promise interface
anim.finished
.then(() => log('Promise: anim.finished resolved!'))
.catch(() => log('Promise: anim.finished rejected/cancelled'));
}
function cancelAnimation() {
if (anim) anim.cancel();
}
The Animation object exposes live properties including currentTime (elapsed ms), playState ('running', 'paused', etc.), playbackRate, id, and pending. You can also imperatively seek playback by assigning to currentTime.
const telemetryTarget = document.getElementById('telemetryTarget');
const telemetryAnim = telemetryTarget.animate([
{ transform: 'scale(0.85) rotate(0deg)', filter: 'hue-rotate(0deg)' },
{ transform: 'scale(1.2) rotate(180deg)', filter: 'hue-rotate(180deg)' }
], {
id: 'pulse-telemetry-01',
duration: 2400,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out'
});
// Read & scrub currentTime live:
// telemetryAnim.currentTime = scrubbedMsValue;
As zhangxinxu noted, the biggest advantage of Web Animations over CSS3 is runtime flexibility. Keyframes, trajectories, scales, and colors can be dynamically calculated in JavaScript at the exact moment of user interaction and cleaned up automatically via onfinish.
function launchParticle(container, originX, originY) {
const dot = document.createElement('div');
dot.className = 'burst-dot';
dot.style.left = originX + 'px';
dot.style.top = originY + 'px';
container.appendChild(dot);
const angle = Math.random() * Math.PI * 2;
const distance = 60 + Math.random() * 100;
const destX = Math.cos(angle) * distance;
const destY = Math.sin(angle) * distance;
const hue = Math.floor(Math.random() * 360);
const anim = dot.animate([
{ transform: 'translate(0, 0) scale(1)', opacity: 1, backgroundColor: `hsl(${hue}, 95%, 65%)` },
{ transform: `translate(${destX}px, ${destY}px) scale(0)`, opacity: 0, backgroundColor: `hsl(${hue + 45}, 90%, 50%)` }
], {
duration: 600 + Math.random() * 600,
easing: 'cubic-bezier(0.1, 0.9, 0.2, 1)',
fill: 'forwards'
});
anim.onfinish = () => dot.remove();
}