ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
SVG & HTML5 Canvas Tutorial• 7 min read
60fps Animations: requestAnimationFrame & Delta Time
The game loop: Clear, update physics, render, and smooth frame timing
Fluid canvas animations rely on the browser requestAnimationFrame() API, syncing screen redraws to the monitor refresh rate (typically 60Hz or 120Hz).
The Canonical Game Loop Architecture
1Clear:
ctx.clearRect(0, 0, canvas.width, canvas.height) wipes the frame.2Update: Update object positions based on elapsed delta time (
dx = vx * dt).3Render: Draw the updated shapes.
4Loop: Call
requestAnimationFrame(gameLoop) to queue the next frame.Bouncing Ball Animation Loop
let x = 50, y = 50;
let vx = 4, vy = 3;
const radius = 20;
function animate() {
// 1. Clear frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2. Update physics & handle edge bounces
x += vx;
y += vy;
if (x + radius > canvas.width || x - radius < 0) vx = -vx;
if (y + radius > canvas.height || y - radius < 0) vy = -vy;
// 3. Render ball
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = "#38bdf8";
ctx.fill();
// 4. Request next frame
requestAnimationFrame(animate);
}
// Start animation loop
requestAnimationFrame(animate);Syncs with the browser vertical sync for tear-free 60fps rendering.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Why is `requestAnimationFrame()` preferred over `setInterval(fn, 16)` for web canvas animations?