Using requestAnimationFrame for Smooth Animations (Live Playground)
The requestAnimationFrame
function is a browser API that allows you to create smooth and efficient animations by calling a specified function before the browser performs the next repaint. This ensures that your animations are in sync with the browser's refresh rate, leading to smoother animations and better performance.
Why use requestAnimationFrame?
Using requestAnimationFrame
has several benefits:
- Optimized frame rate: The browser adjusts the frame rate based on the device's performance, ensuring a consistent experience across different devices.
- Reduced CPU usage: The function is not called when the tab is inactive or minimized, which helps reduce CPU usage and saves battery life on mobile devices.
- Better synchronization: Animations are synchronized with the browser's refresh rate, reducing jank and providing smoother animations.
How to use requestAnimationFrame
To use requestAnimationFrame
, you need to pass a callback function as an argument. The callback function will be executed before the next repaint, and it typically contains the code for updating your animation.
Here's a simple example of using requestAnimationFrame
to create a smooth animation:
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
</style>
<script>
let posX = 0;
const speed = 2;
function animate() {
// Update the position of the box
posX += speed;
// Apply the new position to the box
const box = document.querySelector('.box');
box.style.transform = `translateX(${posX}px)`;
// Request the next frame
requestAnimationFrame(animate);
}
window.addEventListener('DOMContentLoaded', () => {
// Start the animation
requestAnimationFrame(animate);
});
</script>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example, we use requestAnimationFrame
to move a box smoothly across the screen. The animate
function is called repeatedly, updating the position of the box and requesting the next frame.
By using requestAnimationFrame
, you can create smooth and efficient animations that are optimized for performance and provide a better user experience.