Canvas API Basics

Course 3 · Ch 2
Canvas API Basics
Drawing pixel-based graphics directly with JavaScript, and the animation loop that makes them move

<canvas> is a blank rectangular surface that JavaScript draws onto pixel by pixel — shapes, images, text, entire game frames. Unlike every element covered so far, canvas content isn't part of the DOM at all once drawn; it's genuinely just pixels, with no individual shapes to inspect or style with CSS afterward.

Setting Up a Canvas

<canvas id="myCanvas" width="300" height="200"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // the actual drawing API lives on this object </script>
Set width/height as HTML attributes, not CSS, for the actual drawing surface size
CSS width/height resize the canvas's display size, but the drawing surface's internal pixel resolution stays whatever the HTML attributes specified — mismatching the two stretches or blurs everything drawn. Set the real resolution via the HTML attributes; use CSS only if deliberately scaling the display size separately from that resolution.

Basic Drawing

// A filled rectangle ctx.fillStyle = '#e34c26'; ctx.fillRect(20, 20, 100, 60); // x, y, width, height // A circle (canvas has no built-in circle — use an arc spanning the full 360°) ctx.beginPath(); ctx.arc(200, 100, 40, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle ctx.fillStyle = '#58a6ff'; ctx.fill(); // Text ctx.font = '20px sans-serif'; ctx.fillStyle = '#1a1a1a'; ctx.fillText('Hello Canvas', 20, 150);
Hello Canvas

The (0,0) Origin and Coordinate System

Canvas coordinates start at (0,0) in the top-left corner, with X increasing rightward and Y increasing downward — the opposite of typical mathematical graphing convention, but consistent with how most computer graphics systems work, including CSS positioning.

The Animation Loop — requestAnimationFrame

Animating on canvas means redrawing the entire frame repeatedly, slightly differently each time — requestAnimationFrame is the browser-native way to schedule that redraw at the right rate, synced to the display's actual refresh rate.

let x = 0; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // erase the previous frame entirely ctx.fillStyle = '#3fb950'; ctx.fillRect(x, 80, 40, 40); x += 2; // move slightly each frame if (x > canvas.width) x = 0; // wrap around requestAnimationFrame(draw); // schedule the next frame } requestAnimationFrame(draw); // kick off the loop
Forgetting clearRect leaves a smeared trail of every previous frame
Each call to draw() paints on top of whatever's already there — without clearing first, the moving square from the example above would leave a solid streak across the canvas rather than appearing to move cleanly. clearRect (or repainting the entire background) at the start of every frame is essentially mandatory for any genuine animation.

Canvas vs SVG — Choosing the Right Tool

🖼️ Canvas
Pixel-based — once drawn, individual shapes can't be selected, styled with CSS, or queried in the DOM. Better for many objects, frequent redraws, genuinely pixel-level work (image filters, particle effects, games).
📐 SVG (Chapter 3)
Vector/DOM-based — every shape is a real, individually addressable element, stylable with CSS, scales perfectly at any zoom level. Better for icons, diagrams, charts, and anything needing CSS styling or DOM-level interactivity per shape.
A rough rule of thumb: hundreds of simple shapes favours canvas, a few dozen complex ones favours SVG
Canvas's pixel-based, no-DOM-overhead approach scales better to large numbers of objects redrawn every frame (particle systems, simple games). SVG's per-element DOM approach scales better when individual elements need their own styling, event handlers, or accessibility attributes — exactly the trade-off explored in full in Chapter 3.

Chapter 2 Quick Reference

  • canvas.getContext('2d') — the object the actual drawing API lives on
  • Set width/height as HTML attributes, not CSS, for the real drawing resolution
  • fillRect/arc/fillText — basic shape and text drawing
  • Coordinate origin (0,0) is top-left; Y increases downward
  • requestAnimationFrame — schedules the next frame, synced to display refresh rate
  • clearRect at the start of every frame — essential, or previous frames smear together
  • Canvas (pixels, many objects) vs SVG (DOM, stylable elements) — pick based on object count and styling needs
  • Next chapter: SVG in HTML — inline SVG, manipulating with CSS/JS