Web Animations API
Element.animate(), keyframes, timing options, and performance.
Overview
The Web Animations API provides powerful animation capabilities.
Key Concepts
- animate() — Create animations on elements
- Keyframes — Define animation states
- Timing Options — Duration, easing, iterations
- Animation Control — Play, pause, reverse
- Performance — Hardware-accelerated animations
Code Examples
<div id="box" style="width: 100px; height: 100px; background: #007bff;"></div>
<button id="animate">Animate</button>
<script>
const box = document.getElementById('box');
document.getElementById('animate').addEventListener('click', () => {
const animation = box.animate(
[
{ transform: 'translateX(0)', background: '#007bff' },
{ transform: 'translateX(200px)', background: '#28a745' },
{ transform: 'translateX(0)', background: '#007bff' }
],
{
duration: 1000,
easing: 'ease-in-out',
iterations: Infinity,
direction: 'alternate'
}
);
// Control animation
animation.pause();
animation.play();
animation.reverse();
});
// Chained animations
async function chainAnimations() {
await box.animate(
[{ transform: 'scale(1)' }, { transform: 'scale(1.2)' }],
{ duration: 300, fill: 'forwards' }
).finished;
await box.animate(
[{ transform: 'rotate(0deg)' }, { transform: 'rotate(360deg)' }],
{ duration: 500 }
).finished;
}
// Scroll-triggered animation
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.animate(
[{ opacity: 0, transform: 'translateY(20px)' }, { opacity: 1, transform: 'translateY(0)' }],
{ duration: 500, fill: 'forwards' }
);
}
});
});
document.querySelectorAll('.animate-on-scroll').forEach(el => {
observer.observe(el);
});
</script>
Practice
Create scroll-triggered animations using the Web Animations API.