๐ŸŽจ JavaScript

Canvas API Basics โ€” Draw, Animate and Build a Particle Effect

๐Ÿ“… Jul 4, 2026 โฑ 4 min read

Canvas is pixel-level drawing with JavaScript โ€” games, charts, and those floating-particle hero backgrounds.

The basics

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = innerWidth; canvas.height = 400;

ctx.fillStyle = "#6d6ffb";
ctx.fillRect(20, 20, 120, 60);                 // rectangle

ctx.beginPath();
ctx.arc(200, 60, 30, 0, Math.PI * 2);          // circle
ctx.fill();

ctx.strokeStyle = "#fff"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(0, 100); ctx.lineTo(300, 150); ctx.stroke();

ctx.font = "20px Inter"; ctx.fillText("Hello Canvas", 20, 200);

The animation loop

function loop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);   // wipe
  update();                                            // move things
  draw();                                              // repaint
  requestAnimationFrame(loop);                         // ~60fps, pauses in background tabs
}
loop();

Particles in 15 lines

const dots = Array.from({ length: 60 }, () => ({
  x: Math.random() * canvas.width,
  y: Math.random() * canvas.height,
  vx: (Math.random() - 0.5) * 0.6,
  vy: (Math.random() - 0.5) * 0.6,
}));

function update() {
  for (const d of dots) {
    d.x = (d.x + d.vx + canvas.width) % canvas.width;
    d.y = (d.y + d.vy + canvas.height) % canvas.height;
  }
}
function draw() {
  ctx.fillStyle = "rgba(109,111,251,.7)";
  for (const d of dots) { ctx.beginPath(); ctx.arc(d.x, d.y, 2, 0, 7); ctx.fill(); }
}

Build it live in the Playground โ€” instant gratification guaranteed.

โ† All Articles