Chapter 21 of 26

Canvas & SVG

So far, every picture on our pages has come from an image file loaded with <img> or <picture> (see the Images and Responsive Images: srcset & picture chapters). But what if you want to draw something yourself: a chart of your semester marks, a game, a signature pad, or a logo that stays sharp at any size?

HTML gives you two tools for this: <canvas> and <svg>. Both draw graphics, but they work in completely different ways. Knowing that difference is the key idea of this chapter, and it is a favourite interview question.


Raster vs Vector Graphics

Before touching any code, we need two words.

A raster (bitmap) image is a grid of coloured pixels. A vector image is a list of shapes described by mathematics (points, lines, curves).

Think of a raster image as a mosaic made of tiny tiles, and a vector image as a set of instructions like "draw a circle of radius 30 centred at (50, 50)". If you zoom into the mosaic, you see the tiles (it becomes blocky). If you zoom into the instructions, the computer simply redraws the circle bigger, so it stays perfectly sharp.

Property

Raster (bitmap)

Vector

Stored as

Pixels

Shapes and paths

Zooming in

Becomes blurry or blocky

Stays sharp

Good for

Photos, complex textures

Logos, icons, diagrams, charts

File examples

JPEG, PNG, WebP, AVIF

SVG

HTML drawing tool

<canvas> (you paint pixels)

<svg> (you describe shapes)


The <canvas> Element

<canvas> is a rectangular area of pixels on the page that you draw on using JavaScript.

On its own, a canvas is just a blank, transparent rectangle. HTML only creates the drawing surface; all the drawing is done by a script.

<canvas id="board" width="400" height="200">
  A rectangle, a triangle, a circle and the words Hello Canvas.
</canvas>
  • width and height set the size of the drawing surface in pixels. If you leave them out, the canvas is 300 × 150 pixels by default.

  • The content between the tags is fallback content. Browsers that support canvas don't display it. Use it for a text description of what the drawing shows.

  • The closing tag </canvas> is required (unlike <img>, canvas is not a void element).

Attribute Size vs CSS Size

This catches many beginners. A canvas has two sizes:

width/height attributes  →  how many pixels the drawing surface has
CSS width/height         →  how big the box looks on the screen

If you write <canvas width="100" height="50"> and then use CSS to show it 400px wide, the browser stretches 100 pixels across 400 pixels of screen, and your drawing looks blurry. Always set the drawing size with the attributes (or with canvas.width in JavaScript).


Drawing on a Canvas with JavaScript

Drawing always follows the same three steps:

  1. Find the canvas element.

  2. Ask it for a drawing context with getContext("2d"). The context is an object full of drawing methods.

  3. Call those methods to paint.

The Coordinate System

Canvas coordinates start at the top-left corner. x increases to the right, and y increases downwards (the opposite of the graphs in your maths book).

(0,0) ────────────── x increases ──────────► (400,0)
  │
  │      ● (100, 50)  = 100 px right, 50 px down
  │
  y increases
  │
  ▼
(0,200)                                      (400,200)

A Complete Example

Here is a full page that draws a rectangle, a triangle, a circle and some text. Save it as canvas.html and open it in your browser.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Canvas Basics</title>
</head>
<body>
  <h1>Canvas Basics</h1>

  <canvas id="board" width="400" height="200">
    A rectangle, a triangle, a circle and the words Hello Canvas.
  </canvas>

  <script>
    const canvas = document.getElementById("board");
    const ctx = canvas.getContext("2d");

    // 1. A light grey background covering the whole canvas
    ctx.fillStyle = "#eeeeee";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 2. A filled blue rectangle
    ctx.fillStyle = "steelblue";
    ctx.fillRect(20, 20, 100, 60);

    // 3. A red triangle outline (a path)
    ctx.beginPath();
    ctx.moveTo(160, 80);
    ctx.lineTo(210, 20);
    ctx.lineTo(260, 80);
    ctx.closePath();
    ctx.strokeStyle = "crimson";
    ctx.lineWidth = 4;
    ctx.stroke();

    // 4. A green circle
    ctx.beginPath();
    ctx.arc(330, 50, 30, 0, 2 * Math.PI);
    ctx.fillStyle = "seagreen";
    ctx.fill();

    // 5. Some text
    ctx.fillStyle = "black";
    ctx.font = "24px sans-serif";
    ctx.fillText("Hello Canvas", 20, 150);
  </script>
</body>
</html>

Output (what the browser shows):

Under the "Canvas Basics" heading, a 400 × 200 light grey box containing:
  • a filled blue rectangle at the top-left
  • a red triangle outline in the middle
  • a filled green circle at the top-right
  • the text "Hello Canvas" below them

Let's go through the important methods:

Code

What it does

ctx.fillStyle = "steelblue"

Sets the colour for the next fills (any CSS colour works)

ctx.fillRect(x, y, w, h)

Draws a filled rectangle with its top-left corner at (x, y)

ctx.strokeRect(x, y, w, h)

Draws only the outline of a rectangle

ctx.clearRect(x, y, w, h)

Erases that area back to transparent

ctx.beginPath()

Starts a new shape (a path)

ctx.moveTo(x, y)

Lifts the "pen" and moves it without drawing

ctx.lineTo(x, y)

Adds a straight line to (x, y)

ctx.closePath()

Joins the last point back to the first

ctx.arc(x, y, r, start, end)

Adds a circle or arc; angles are in radians

ctx.stroke() / ctx.fill()

Actually paints the current path (outline / filled)

ctx.fillText(text, x, y)

Draws text; by default y is the text's baseline, not its top

Two details deserve attention:

  • Paths do nothing until you call stroke() or fill(). moveTo() and lineTo() only plan the shape.

  • A full circle is 0 to 2 * Math.PI radians (360° = 2π radians). Angle 0 points to the right (3 o'clock), and by default angles go clockwise.

Why beginPath() Matters

If you forget beginPath() before the circle, the circle is added to the same path as the triangle. Then fill() would also fill the triangle green. Rule of thumb: call beginPath() before every new shape that isn't drawn with a rectangle method like fillRect().


Worked Example: A Bar Chart of Marks

Canvas really shines when the drawing comes from data. Let's draw a bar chart from an array of marks. Bars for 75 and above are green; the rest are orange.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Marks Chart</title>
</head>
<body>
  <h1>Semester Marks</h1>

  <canvas id="chart" width="420" height="260">
    Bar chart of marks: Maths 78, Physics 64, C Programming 92, English 55.
  </canvas>

  <script>
    const marks = [
      { subject: "Maths", score: 78 },
      { subject: "Physics", score: 64 },
      { subject: "C Prog", score: 92 },
      { subject: "English", score: 55 }
    ];

    const canvas = document.getElementById("chart");
    const ctx = canvas.getContext("2d");

    const baseY = 220;      // y of the x-axis
    const barWidth = 60;
    const gap = 40;
    ctx.font = "14px sans-serif";

    // x-axis
    ctx.beginPath();
    ctx.moveTo(20, baseY);
    ctx.lineTo(410, baseY);
    ctx.stroke();

    marks.forEach((item, i) => {
      const x = 40 + i * (barWidth + gap);
      const barHeight = item.score * 2;   // 1 mark = 2 pixels

      ctx.fillStyle = item.score >= 75 ? "seagreen" : "darkorange";
      ctx.fillRect(x, baseY - barHeight, barWidth, barHeight);

      ctx.fillStyle = "black";
      ctx.fillText(item.score, x + 20, baseY - barHeight - 6);
      ctx.fillText(item.subject, x + 5, baseY + 18);
    });
  </script>
</body>
</html>

Output:

                   92
      78           ██
      ██           ██
      ██    64     ██
      ██    ██     ██    55
      ██    ██     ██    ██
      ██    ██     ██    ██
  ────██────██─────██────██────
     Maths Physics C Prog English

(Maths and C Prog bars are green, Physics and English bars are orange,
 with each score written above its bar.)

How the numbers were worked out, for the first bar (Maths, 78):

x         = 40 + 0 × (60 + 40)   = 40
barHeight = 78 × 2               = 156
top y     = baseY − barHeight    = 220 − 156 = 64
fillRect(40, 64, 60, 156)        → a bar from y = 64 down to y = 220

Because y grows downwards, a taller bar starts higher (smaller y). That's why we subtract the height from the axis position.


Canvas is "Fire and Forget"

This is the most important property of canvas:

Canvas works in immediate mode: once a shape is painted, the canvas only remembers the pixels, not the shape.

After fillRect() runs, there is no "rectangle object" you can select, move or recolour. To move it, you must clear the canvas and draw everything again in the new position. Games and animations do exactly this, many times per second, usually with requestAnimationFrame():

const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");
let x = 0;

function frame() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // wipe everything
    ctx.fillStyle = "steelblue";
    ctx.fillRect(x, 70, 50, 50);                        // draw at the new x
    x = (x + 2) % canvas.width;                         // move 2 px per frame
    requestAnimationFrame(frame);                       // ask for the next frame
}

frame();

This draws a square that slides across the canvas and wraps around to the left edge. The browser calls frame() before each screen repaint, which is usually in step with the display's refresh rate (about 60 times a second on a 60 Hz screen).

Since a canvas is just pixels, you can also save it as an image: canvas.toDataURL("image/png") returns the picture as a data: URL. (If you drew an image loaded from another website without permission, the canvas becomes "tainted" and the browser blocks this, for security.)

Besides "2d", getContext() also accepts "webgl" and "webgl2" for hardware-accelerated 3D graphics, which is how many browser games and 3D viewers work.


SVG: Scalable Vector Graphics

SVG is an XML-based language for describing vector graphics. Each shape is an element (like <circle> or <rect>) with attributes for its position, size and colour.

Unlike canvas, SVG needs no JavaScript. You write the shapes as markup, right inside your HTML. Here is the same drawing as before, now in SVG:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SVG Shapes</title>
</head>
<body>
  <h1>SVG Shapes</h1>

  <svg width="400" height="200" viewBox="0 0 400 200">
    <rect x="0" y="0" width="400" height="200" fill="#eeeeee" />
    <rect x="20" y="20" width="100" height="60" fill="steelblue" />
    <polygon points="160,80 210,20 260,80"
             fill="none" stroke="crimson" stroke-width="4" />
    <circle cx="330" cy="50" r="30" fill="seagreen" />
    <line x1="20" y1="110" x2="380" y2="110" stroke="black" stroke-dasharray="6 4" />
    <text x="20" y="150" font-size="24" font-family="sans-serif">Hello SVG</text>
  </svg>
</body>
</html>

Output:

The same picture as the canvas version (grey box, blue rectangle,
red triangle outline, green circle), plus a dashed horizontal line,
and the text "Hello SVG".

When SVG is written inline inside an HTML page like this, you don't need the xmlns attribute; the HTML parser knows that everything inside <svg> is SVG. A standalone .svg file, on the other hand, must declare it: <svg xmlns="http://www.w3.org/2000/svg" ...>.

Notice the /> at the end of the shapes. SVG elements follow XML rules, so an empty shape can be written as a self-closing tag, and this is allowed for SVG elements inside HTML.

Basic SVG Shapes

Element

Key attributes

Draws

<rect>

x, y, width, height, rx (rounded corners)

Rectangle

<circle>

cx, cy (centre), r (radius)

Circle

<ellipse>

cx, cy, rx, ry

Ellipse

<line>

x1, y1, x2, y2

Straight line (needs a stroke to be visible)

<polyline>

points

Connected lines, left open

<polygon>

points

Connected lines, closed automatically

<path>

d (drawing commands)

Any shape at all

<text>

x, y (baseline position)

Text

Colours come from fill (inside colour, default black) and stroke (outline colour, default none), plus stroke-width for the outline thickness. The SVG coordinate system is the same as canvas: origin at the top-left, y pointing down.

The viewBox Attribute

viewBox="minX minY width height" defines the SVG's internal coordinate system. The width and height attributes decide how big it appears on the page. The browser scales one to fit the other.

<svg width="160" height="160" viewBox="0 0 100 100">

internal units:  0 … 100  (what your shapes use)
on screen:       0 … 160 px
scale factor:    160 ÷ 100 = 1.6  → a circle with r="45" appears 72 px in radius

This is what makes SVG "scalable": draw your icon once in a 100 × 100 box, then show it at 16 px or 600 px simply by changing width and height, and it stays sharp.

The <path> Element

<path> is the most powerful shape. Its d attribute is a mini-language of pen commands:

Command

Meaning

Example

M x y

Move to (pen up)

M 10 10

L x y

Line to

L 90 10

H x / V y

Horizontal / vertical line

H 50

Q, C

Quadratic / cubic Bézier curve

Q 50 0 90 50

A

Elliptical arc

A 20 20 0 0 1 50 50

Z

Close the path

Z

Uppercase commands use absolute coordinates; lowercase commands (m, l, ...) are relative to the current pen position. Design tools like Figma, Inkscape and Illustrator export icons as long d strings; you rarely write complex ones by hand.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SVG Logo</title>
  <style>
    .badge:hover circle { fill: gold; }
  </style>
</head>
<body>
  <svg class="badge" width="160" height="160" viewBox="0 0 100 100"
       role="img" aria-labelledby="logo-title">
    <title id="logo-title">CS Club logo</title>
    <circle cx="50" cy="50" r="45" fill="navy" />
    <path d="M 30 35 L 15 50 L 30 65 M 70 35 L 85 50 L 70 65"
          fill="none" stroke="white" stroke-width="6" stroke-linecap="round" />
    <text x="50" y="58" text-anchor="middle" font-size="22"
          font-family="monospace" fill="white">CS</text>
  </svg>

  <svg width="80" height="80" viewBox="0 0 100 100" role="img" aria-label="Small CS Club logo">
    <circle cx="50" cy="50" r="45" fill="navy" />
    <text x="50" y="58" text-anchor="middle" font-size="22"
          font-family="monospace" fill="white">CS</text>
  </svg>
</body>
</html>

Output:

Two navy circles side by side: a large one (160 px) showing "< CS >" in
white, with the angle brackets drawn by the path, and a smaller one (80 px)
showing just "CS". Hovering over the large logo turns its circle gold.

Notice three things that canvas can't do so easily:

  • CSS works on SVG shapes. The rule .badge:hover circle { fill: gold; } recolours the circle on hover, because each shape is a real element in the DOM.

  • One path, two shapes. The d string uses two M commands, so a single <path> draws both brackets.

  • Accessibility is built in. role="img" tells assistive technology to treat the SVG as one image, and the <title> (linked with aria-labelledby) or aria-label gives it a name, just like alt on <img>. If an SVG is purely decorative, use aria-hidden="true" instead.

Three Ways to Use SVG

Method

Example

Can page CSS/JS reach the shapes?

Inline in HTML

<svg>...</svg>

Yes

As an image

<img src="logo.svg" alt="CS Club logo">

No (it behaves like any image; scripts inside it don't run)

As a CSS background

background-image: url("pattern.svg")

No

Use <img> for logos and illustrations that never change (the file can be cached and reused across pages). Use inline SVG for icons you want to recolour with CSS or animate.


Canvas vs SVG

Feature

<canvas>

<svg>

Type

Raster (pixels)

Vector (shapes)

How you draw

JavaScript only

Markup (JavaScript optional)

Mode

Immediate: forgets shapes after painting

Retained: every shape is a DOM element

Zooming / resizing

Can become blurry

Always sharp

Events (click, hover)

Only on the whole canvas; you calculate which shape was hit

On each individual shape

Styling with CSS

Only the canvas box

Each shape

Performance

Handles thousands of objects and per-pixel work well

Slows down with very many elements (each one is in the DOM)

Accessibility

Opaque to screen readers; you must add a text alternative

Can carry titles and real text

Typical uses

Games, photo editors, particle effects, video processing, large live charts

Logos, icons, diagrams, maps, interactive charts, illustrations

A simple way to remember it: canvas is a painting, SVG is a set of stickers. Once paint is on the canvas you can only paint over it; stickers can be picked up, moved and recoloured one by one.


Common Mistakes

  • Sizing the canvas only with CSS. The drawing surface stays 300 × 150 and gets stretched, so everything is blurry. Set the width and height attributes.

  • Running the script before the canvas exists. If the <script> is in the <head> without defer, getElementById() returns null. Put the script after the canvas or use defer.

  • Forgetting beginPath(), so new shapes join the old path and get filled or stroked together.

  • Using degrees in arc(). ctx.arc(50, 50, 20, 0, 360) is wrong; use 2 * Math.PI.

  • Expecting to click a canvas shape. Canvas has no shapes after drawing; use SVG if you need per-shape interaction.

  • Forgetting stroke on an SVG <line>. A line has no inside to fill, so without a stroke it is invisible.

  • No text alternative. A canvas chart with no description means nothing to a screen reader user. We'll go deeper into this in the Accessibility Basics chapter.


Interview Questions

What is the difference between canvas and SVG?

Canvas is a raster drawing surface controlled by JavaScript; it works in immediate mode and keeps only pixels. SVG is a vector format where each shape is a DOM element (retained mode), so shapes can be styled with CSS, receive events, and scale without losing quality. Canvas is better for many objects or pixel-level work (games, image editing); SVG is better for icons, logos, diagrams and interactive charts with fewer elements.

What is the default size of a canvas element?

300 pixels wide and 150 pixels high, when the width and height attributes are not given.

Why does a canvas look blurry when resized with CSS?

CSS changes only the displayed size. The number of pixels in the drawing surface is still set by the width and height attributes, so the browser stretches those pixels to fill the bigger box.

What does the viewBox attribute of an SVG do?

It defines the internal coordinate system as minX minY width height. The browser maps that region onto the element's displayed size, which is what lets the same SVG scale cleanly to any size.

Which would you pick for a game with 5,000 moving particles, and why?

Canvas. Redrawing 5,000 particles as pixels each frame is cheap, whereas 5,000 SVG elements would all live in the DOM, and updating each of them every frame would be slow.

How do you make an inline SVG accessible?

Give it role="img" and an accessible name, either with aria-label or with a <title> child referenced by aria-labelledby. If it's purely decorative, hide it with aria-hidden="true".

Conclusion

  • <canvas> is a pixel surface you paint with JavaScript through getContext("2d"). It's fast, but it forgets shapes as soon as they're drawn.

  • Set canvas size with the width/height attributes (default 300 × 150). Coordinates start at the top-left, with y going down.

  • <svg> describes shapes as elements (rect, circle, path, ...). They stay sharp at any size, and can be styled, animated and made accessible.

  • viewBox sets SVG's internal coordinates and makes scaling possible.

  • Choose canvas for games, pixels and huge numbers of objects; choose SVG for logos, icons, diagrams and interactive graphics.

Next, in Modern Elements: dialog, details & summary, we'll see how HTML now gives you pop-up dialogs and collapsible sections with very little (or no) JavaScript.