The three drawing steps of every Canvas visual

We can deconstruct a Canvas drawing into three simple steps:

  1. Create the canvas and its context.
  2. Configure the context.
  3. Render the resulting bitmap.

To mount the canvas within your DOM you create a <canvas> element in HTML:

<canvas id=”main-canvas” width = “600” height=”400”></canvas>

It will look empty, as expected:

An empty Canvas element

This will be all the DOM you will see of your canvas. All other operations will happen via the Canvas context in JavaScript.

If you wanted to draw a rectangle in, say, royalblue, you would move onto JavaScript without looking back to the HTML and write:

Get Learning D3.js 5 Mapping - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.