HTML Β· Module 10 Β· Lesson 49 of 54

HTML5 Drawing Canvas

What is the Canvas API?

Imagine a blank whiteboard. An SVG is like sticky shapes you place on the boardβ€”you can move them around as separate objects. A <canvas> is like dry-erase markers: you have a raw pixel grid, and you write code telling a robotic marker exactly where to draw lines and fill blocks.

The <canvas> tag allocates a drawing board area. On its own, it has no graphics. You must use JavaScript scripting to target the canvas context and dynamically render animations, drawing apps, or 2D game frames.

Why does it matter?

While SVGs are best for vector logos and icons, <canvas> is best for highly dynamic, high-performance rendering. It is the engine behind modern HTML5 browser games, interactive data visualizations, and image editors.

How to write it

Declare the canvas container with width and height in HTML, then draw on it using JavaScript:
<canvas id="game-board" width="200" height="200"></canvas>

<canvas> context

Common Mistakes

  • Sizing the canvas with CSS instead of attributes: If you set the width and height of a canvas in CSS (e.g., width: 200px), it stretches the canvas like an image, causing the drawings inside to look blurry. Always set the width and height attributes directly on the HTML tag!
  • Quick Reference

  • <canvas id="id" width="w" height="h"> β€” Allocates a script-drawable grid.
  • Your Task
    Create a `<canvas>` element with `id="game-board"`, `width="200"`, and `height="200"`.
    index.html
    Type code above to start the lesson.
    Live Preview