0
0
HtmlHow-ToBeginner · 3 min read

How to Animate Canvas in HTML: Simple Steps and Example

To animate a canvas in HTML, use the <canvas> element with JavaScript to draw and update graphics repeatedly. Use requestAnimationFrame() to create smooth animations by redrawing the canvas content in a loop.
📐

Syntax

To animate on a canvas, you first get the drawing context from the <canvas> element. Then, use requestAnimationFrame() to create a loop that updates and redraws your shapes or images.

  • canvas.getContext('2d'): Gets the 2D drawing context.
  • requestAnimationFrame(callback): Calls the callback before the next repaint for smooth animation.
  • clearRect(): Clears the canvas to redraw fresh frames.
  • Draw shapes or images inside the animation loop.
javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
  // Draw shapes here
  requestAnimationFrame(animate); // Loop
}

animate();
💻

Example

This example shows a blue circle moving horizontally across the canvas. It uses requestAnimationFrame() to update the circle's position smoothly.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Animation Example</title>
  <style>
    body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f0f0f0; }
    canvas { background: white; border: 1px solid #ccc; }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="400" height="150" aria-label="Animated blue circle moving horizontally"></canvas>
  <script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    let x = 0;
    const y = canvas.height / 2;
    const radius = 20;
    const speed = 2;

    function animate() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2);
      ctx.fillStyle = 'blue';
      ctx.fill();
      x += speed;
      if (x - radius > canvas.width) {
        x = -radius; // Reset to start from left again
      }
      requestAnimationFrame(animate);
    }

    animate();
  </script>
</body>
</html>
Output
A white rectangular canvas with a blue circle smoothly moving from left to right repeatedly.
⚠️

Common Pitfalls

  • Not clearing the canvas each frame causes drawing to stack and blur.
  • Using setTimeout or setInterval instead of requestAnimationFrame can cause choppy animations.
  • Forgetting to update positions or states inside the animation loop stops movement.
  • Not setting canvas width and height attributes properly can distort the drawing.
javascript
/* Wrong way: No clearing, using setInterval */
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
setInterval(() => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, 75, 20, 0, Math.PI * 2);
  ctx.fillStyle = 'red';
  ctx.fill();
  x += 5;
}, 30);

/* Right way: Clear and use requestAnimationFrame */
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, 75, 20, 0, Math.PI * 2);
  ctx.fillStyle = 'red';
  ctx.fill();
  x += 5;
  if (x - 20 > canvas.width) x = -20;
  requestAnimationFrame(animate);
}
animate();
📊

Quick Reference

  • Get context: canvas.getContext('2d')
  • Clear canvas: ctx.clearRect(0, 0, width, height)
  • Draw shapes: ctx.beginPath(), ctx.arc(), ctx.fill()
  • Animate: Use requestAnimationFrame() for smooth loops
  • Update state: Change positions or properties inside the animation function

Key Takeaways

Use requestAnimationFrame() to create smooth, efficient canvas animations.
Always clear the canvas each frame with clearRect() before redrawing.
Update your shapes' positions inside the animation loop to create movement.
Set canvas width and height attributes properly to avoid distortion.
Avoid using setTimeout or setInterval for animations.