SyntaxStudy
Sign Up
HTML Canvas Animation with requestAnimationFrame
HTML Intermediate 6 min read

Canvas Animation with requestAnimationFrame

Canvas Animation

requestAnimationFrame() schedules a callback before the next screen repaint, producing smooth 60fps animations. Clear the canvas and redraw everything each frame.

Example
const ctx = canvas.getContext("2d");
let x = 0;
let animId;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = "#007bff";
  ctx.beginPath();
  ctx.arc(x, 100, 30, 0, Math.PI * 2);
  ctx.fill();

  x = (x + 2) % canvas.width;
  animId = requestAnimationFrame(animate);
}

animate(); // Start
// cancelAnimationFrame(animId); // Stop
Pro Tip

Store the requestAnimationFrame ID and call cancelAnimationFrame() to stop animations when the element is removed.