Animation with requestAnimationFrame
Build smooth canvas animations with the animation frame loop.
Animation with requestAnimationFrame is a free HTML Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the HTML Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why requestAnimationFrame?
requestAnimationFrame (rAF) schedules a callback before the next browser repaint, synchronizing animation to the display refresh rate (typically 60fps). Unlike setInterval, rAF pauses when the tab is hidden, saving CPU and battery.
Basic Animation Loop
A rAF loop: define an animate function that draws the current frame, then calls requestAnimationFrame(animate) to schedule the next. The browser calls animate before each repaint, creating a continuous animation at the display's frame rate.
function animate(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw frame at current state
draw(timestamp);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);The timestamp Parameter
rAF passes a DOMHighResTimeStamp (milliseconds since page load) to the callback. Use it to calculate frame-rate-independent motion: delta = timestamp - lastTimestamp. Multiply velocity by delta to move the same distance per second regardless of frame rate.
Frame-Rate-Independent Motion
Calculate elapsed time since the last frame and scale movement accordingly. An object moving at 100px/s travels 100 * (delta / 1000) pixels per frame. This ensures consistent physics on 30fps and 144fps displays.
Stopping Animation
rAF returns a handle. Cancel with cancelAnimationFrame(handle). Store the handle in a variable, check a running flag inside the loop, or cancel on component cleanup. Always cancel loops when the element is removed from the DOM.
Canvas Animation Pattern
Each frame: (1) clearRect the entire canvas, (2) update state variables (position, angle, time), (3) draw all objects at new positions, (4) call requestAnimationFrame for the next frame. Never skip clearRect — old frames accumulate as a trail.
CSS Transitions vs rAF
Use CSS transitions and animations for simple, property-based animations (hover effects, modal slide-in). Use rAF for complex, interactive animations — game loops, physics simulations, canvas rendering — where you need fine-grained control over each frame.
Double Buffering on Canvas
For complex scenes, draw on an off-screen canvas first, then drawImage it onto the visible canvas in one operation. This prevents flickering by never showing a partially-drawn frame — the visible canvas updates atomically each frame.
Throttling to Target FPS
Limit to a lower frame rate (e.g., 30fps): check if enough time has elapsed since the last draw before rendering. if (timestamp - lastDraw >= 1000/30) { draw(); lastDraw = timestamp; }. Schedule rAF regardless to maintain responsiveness.
Debugging Animation
Chrome DevTools Performance panel records rAF callbacks in the JS flame chart. Look for long callbacks that exceed 16ms — they cause dropped frames. Use the FPS meter (Rendering → FPS Meter) to observe real-time frame rate during interaction.
Web Animations API Alternative
For simpler declarative animations without manual timing: element.animate(keyframes, options). WAAPI handles timing functions, fill modes, and iteration — offloading frame calculation to the browser. Use rAF for custom rendering logic WAAPI cannot express.
Knowledge Check
Why should animation velocity be multiplied by delta time in a requestAnimationFrame loop?
Summary
requestAnimationFrame synchronizes JavaScript animation to the display refresh rate, pausing on hidden tabs. The timestamp parameter enables frame-rate-independent motion via delta-time scaling. The canvas animation loop pattern (clear, update, draw, schedule) combined with cancelAnimationFrame for cleanup forms the foundation of smooth, efficient web animations.
Frequently asked questions
Is the “Animation with requestAnimationFrame” lesson free?
Yes — the full text of “Animation with requestAnimationFrame” is free to read here on the web, and the HTML Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the HTML Academy course, upgrade to CoddyKit PRO.
What will I learn in “Animation with requestAnimationFrame”?
Build smooth canvas animations with the animation frame loop. You practise HTML Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start HTML Academy?
No prior experience is required. HTML Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Animation with requestAnimationFrame” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this HTML Academy lesson?
Yes. Every HTML Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Setting Up the Canvas and 2D Context
- Drawing Rectangles and Paths
- Text and Images on Canvas
- Animation with requestAnimationFrame