← JS Mastery | Module 8: Web APIs Canvas API & Animation
Module 8

Canvas API & Animation

⏱ 26 min read ● Intermediate 🆓 Free

Canvas Basics

// HTML: <canvas id="c" width="600" height="400"></canvas>
const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");

// Shapes:
ctx.fillStyle = "#f5a623";
ctx.fillRect(10, 10, 100, 60);     // filled rectangle
ctx.strokeStyle = "#fff";
ctx.lineWidth = 2;
ctx.strokeRect(10, 10, 100, 60);   // outline rectangle
ctx.clearRect(20, 20, 30, 20);     // erase area

// Circle:
ctx.beginPath();
ctx.arc(300, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = "#3b82f6";
ctx.fill();

// Line path:
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(600, 400);
ctx.strokeStyle = "red";
ctx.stroke();

// Text:
ctx.font = "bold 28px Space Grotesk";
ctx.fillStyle = "#fff";
ctx.textAlign = "center";
ctx.fillText("Canvas!", 300, 50);

Animation Loop

let x = 0;
const speed = 3;

function animate(timestamp) {
  // Clear:
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // Draw:
  ctx.fillStyle = "#f5a623";
  ctx.beginPath();
  ctx.arc(x, 200, 25, 0, Math.PI * 2);
  ctx.fill();
  
  // Update:
  x = (x + speed) % (canvas.width + 25);
  
  // Loop:
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

// Particle system:
const particles = Array.from({ length: 50 }, () => ({
  x: Math.random() * canvas.width,
  y: Math.random() * canvas.height,
  vx: (Math.random() - 0.5) * 4,
  vy: (Math.random() - 0.5) * 4,
  r: Math.random() * 5 + 2
}));

function drawParticles() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  particles.forEach(p => {
    p.x += p.vx;
    p.y += p.vy;
    if (p.x < 0 || p.x > canvas.width) p.vx *= -1;
    if (p.y < 0 || p.y > canvas.height) p.vy *= -1;
    ctx.beginPath();
    ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
    ctx.fillStyle = "#f5a623";
    ctx.fill();
  });
  requestAnimationFrame(drawParticles);
}
requestAnimationFrame(drawParticles);

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Build an animated clock: draw face, tick marks, and three hands (hour, minute, second). Update every frame using the current time.

← Web Workers