December 31, 2024
Creating smooth and efficient animations is a key aspect of modern web development. JavaScript’s requestAnimationFrame is a game-changing API that helps developers achieve this effortlessly. In this article, I’ll share a deep dive into what requestAnimationFrame is, why it’s different from CSS transition, and a practical example to help you master it.
requestAnimationFrame is a browser-native method designed for scheduling and running animations efficiently. It asks the browser to execute a callback function just before the next repaint, enabling smooth visuals at the optimal refresh rate.
transition
?While both requestAnimationFrame and CSS transition can create animations, they serve different purposes and excel in different scenarios. Here’s how they differ:
<div id="ball" style="width: 50px; height: 50px; background: red; border-radius: 50%; position: absolute; top: 0; left: 50%; transform: translateX(-50%);"></div>
const ball = document.getElementById("ball");
let start = null;
function bounce(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const amplitude = 150; // Maximum bounce height
const frequency = 0.002; // Speed of bounce
const position = amplitude * Math.abs(Math.sin(frequency * progress));
ball.style.top = `${position}px`;
requestAnimationFrame(bounce);
}
// Start the animation
requestAnimationFrame(bounce);
This animation uses a sine wave to simulate a natural bouncing effect.
requestAnimationFrame is an essential tool for creating high-performance animations in modern web development. It offers a clean, efficient way to animate elements, ensuring a seamless experience for users. Whether you’re working on simple transitions or complex animations, this API is a must-have in your toolkit.