Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

Canvas & SVG Graphics

5 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 4 deck

Canvas & SVG Graphics
Fullscreen for presentation · Print / PDF for a handout
1 / 5
Lesson

Canvas & SVG Graphics

Bitmap drawing with Canvas, scalable vector graphics with SVG, and when to use each.

Canvas & SVG Graphics

The HTML5 Canvas Element

The <canvas> element provides a resolution-dependent bitmap surface for JavaScript-driven drawing.

<canvas id="myCanvas" width="400" height="300"></canvas>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a red rectangle
ctx.fillStyle = "rgb(200, 0, 0)";
ctx.fillRect(10, 10, 120, 90);

// Draw a blue rectangle (overlapping)
ctx.fillStyle = "rgba(0, 0, 200, 0.6)";
ctx.fillRect(60, 55, 120, 90);

// Draw a circle
ctx.beginPath();
ctx.arc(250, 150, 60, 0, Math.PI * 2);
ctx.fillStyle = "#0891B2";
ctx.fill();

Canvas capabilities

  • Draw shapes, paths and gradients
  • Render and manipulate images
  • Animate using requestAnimationFrame
  • Capture user events (click, drag)
  • Export the result as PNG or JPEG

Canvas is raster-based — quality degrades when scaled.

Canvas & SVG Graphics

Scalable Vector Graphics (SVG)

Inline SVG in HTML5:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
  <circle cx="60" cy="60" r="40" fill="#0891B2" />
  <rect x="100" y="20" width="80" height="80" fill="#7C3AED" />
  <text x="20" y="160" font-size="18">SVG</text>
</svg>

SVG key properties

  • Resolution independent — scales perfectly at any size
  • Supports event handlers (onclick, onmouseover)
  • Part of the DOM — style with CSS, script with JS
  • Ideal for icons, charts, maps and illustrations
  • Each shape is a separate DOM element
  • Accessible — add title, desc and ARIA attributes
Canvas & SVG Graphics

Canvas vs SVG — When to Use Which?

CriterionCanvasSVG
TypeRaster (pixel-based)Vector (coordinate-based)
ResolutionDependent — blurs when scaledIndependent — crisp at any size
Event handlingNot built-in (manual hit-testing)Native (each shape is a DOM node)
PerformanceFast for many pixels / framesSlower with many DOM elements
Best use casesGames, photo editing, animationCharts, maps, icons, diagrams
AccessibilityLimited without extra workFull ARIA / semantic support
ExportPNG / JPEG snapshotXML file, scalable, editable
Canvas & SVG Graphics

Activity — complete the code

Complete the canvas drawing code and the SVG shape.

<canvas id="art" width="400" height="300"></canvas>
<script>
const ctx = document.getElementById("art").("2d");
ctx. = "#2563eb";
ctx.fillRect(10, 10, 120, 90);
</script>
 
<svg xmlns="http://www.w3.org/2000/svg">
< cx="60" cy="60" r="40" fill="teal" />
</svg>