Canvas API Basics — Creative Web

<canvas width height> is a sheet of pixels (dots of colour), and getContext('2d') gives you the brush, called the context. Point (0, 0) is the top-left corner…

Raka owns a shop called Raka Tees. Its best seller is the Coffee Print Tee ($95). In this track we build a creative site for his shop. In this lesson we draw the tee's coffee print ourselves on a <canvas>, step by step.

A <canvas> is an HTML element that holds a blank sheet of pixels. A pixel is the smallest dot of colour on a screen. You paint the sheet with JavaScript commands such as "fill this box", "draw a line to there" or "write text here".

It works a lot like Raka screen-printing a t-shirt. The ink goes through a screen (a mesh that carries the design), one colour at a time. Once the ink is on, the shirt only has ink on it. Raka can't lift the printed cup off the shirt and move it. To change the picture, he prints a new shirt. A canvas is the same: every command leaves pixels behind, and the canvas doesn't remember that those pixels form a cup.

The canvas and its 2D context

Put a <canvas> element in the HTML:

<canvas id="print" width="300" height="300"></canvas>

Then get its context in JavaScript:

const canvas = document.getElementById('print');
const ctx = canvas.getContext('2d');

The coordinate system

Every point on a canvas has coordinates (x, y): x is the distance from the left edge and y the distance from the top edge, in pixels. Point (0, 0) is the top-left corner. x grows to the right, y grows downwards, the opposite of the graphs in maths class. On a 300 × 300 canvas the bottom-right corner is (300, 300) and the middle is (150, 150).

Angles are written in radians, not degrees. A radian is another unit for angles: half a turn (180°) is Math.PI radians, about 3.14. Because y grows downwards, a positive angle turns clockwise:

Degrees Radians Direction from the centre
0° 0 right (3 o'clock)
90° Math.PI / 2 down (6 o'clock)
180° Math.PI left (9 o'clock)
-90° -Math.PI / 2 up (12 o'clock)
360° Math.PI * 2 one full turn

The coffee print, step by step

Raka uses three colours: shirt black, cream and coffee brown. The space for the steam above the cup (y 30 to 110) is left empty on purpose. The next lesson animates the steam.

const SHIRT = '#1c1917'; // shirt black
const CREAM = '#f5e6c8'; // cream ink
const BROWN = '#c47a3d'; // coffee-brown ink

// 1. The fabric: a box the size of the canvas
ctx.fillStyle = SHIRT;
ctx.fillRect(0, 0, 300, 300);

// 2. The cup's body: a four-point path, narrower at the bottom
ctx.beginPath();
ctx.moveTo(95, 120);
ctx.lineTo(205, 120);
ctx.lineTo(195, 210);
ctx.lineTo(105, 210);
ctx.closePath();
ctx.fillStyle = BROWN;
ctx.fill();

// 3. The cup's outline: the same path, stroked this time
ctx.strokeStyle = CREAM;
ctx.lineWidth = 8;
ctx.stroke();

// 4. The handle: half a circle on the right
ctx.beginPath();
ctx.arc(200, 160, 24, -Math.PI / 2, Math.PI / 2);
ctx.stroke();

// 5. The saucer: one thick line
ctx.beginPath();
ctx.moveTo(75, 228);
ctx.lineTo(225, 228);
ctx.lineWidth = 10;
ctx.stroke();

// 6. The lettering
ctx.font = 'bold 44px sans-serif';
ctx.textAlign = 'center';
ctx.fillStyle = CREAM;
ctx.fillText('BREW', 150, 282);

save, restore and transforms

The coffee beans left and right of the lettering are circles that are squashed and tilted. Instead of calculating their points, we move and turn the paper, which is the canvas's coordinate system, and then draw a plain circle. A change to the coordinate system is called a transform. The bean function does this:

function bean(x, y, angle) {
  ctx.save();              // store the context's current state
  ctx.translate(x, y);     // point (0, 0) moves to (x, y)
  ctx.rotate(angle);       // turn the paper (radians)
  ctx.scale(1, 0.6);       // height becomes 60%: the circle turns oval
  ctx.beginPath();
  ctx.arc(0, 0, 12, 0, Math.PI * 2);
  ctx.fillStyle = BROWN;
  ctx.fill();
  ctx.restore();           // back to the state at save()
}

bean(62, 266, -0.5);
bean(238, 266, 0.5);

A blurry canvas on a retina screen

devicePixelRatio (DPR for short) is how many screen pixels are used for the width of 1 CSS px. It is 1 on a regular laptop screen, 2 on a retina laptop (a screen with more tightly packed pixels), and 2 to 3 on most phones.

A canvas with width="300" and the same height has 300 × 300 = 90,000 pixels. If that canvas is shown 300 CSS px wide on a DPR 2 screen, that area holds 600 × 600 = 360,000 screen pixels. The browser has to stretch every canvas pixel over 2 × 2 screen pixels, and the result is blurry. At DPR 3, 90,000 canvas pixels are stretched over 810,000 screen pixels.

The fix: give the canvas as many pixels as the screen has there, but keep showing it 300 px wide:

const dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(300 * dpr);  // DPR 2: 600 real pixels
canvas.height = Math.round(300 * dpr);
canvas.style.width = '300px';          // displayed size stays 300 px
canvas.style.height = '300px';
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // same as scale(dpr, dpr), without stacking
// ...then draw as usual, still with numbers from 0 to 300

drawImage: pasting another picture

drawImage copies a picture onto the canvas. The source can be an <img>, a <video> or another canvas. In this code, magnifier is the context of a second canvas.

// Raka's logo in the top-right corner, 26 × 26
const logo = new Image();
logo.onload = () => ctx.drawImage(logo, 262, 12, 26, 26);
logo.src = 'raka-logo.png';

// Magnifier: a 24 × 24 box at the cup's bottom-left corner, enlarged 6 times
magnifier.imageSmoothingEnabled = false; // show the pixels as they are
magnifier.drawImage(canvas, 93 * dpr, 198 * dpr, 24 * dpr, 24 * dpr, 0, 0, 144, 144);

⚠️ Why doesn't the print come out the way the code says?

TL;DR: <canvas width height> is a sheet of pixels (dots of colour), and getContext('2d') gives you the brush, called the context. Point (0, 0) is the top-left corner and y grows downwards. Angles are written in radians (half a turn is Math.PI) and turn clockwise. fillRect(x, y, width, height) fills a box that starts at its top-left corner. A path is a chain of lines that stays invisible until you call fill (fill it) or stroke (draw its outline). You build it with beginPath, moveTo (move without drawing), lineTo (draw a line), arc (an arc; a full circle runs from 0 to Math.PI * 2) and closePath, with fillStyle/strokeStyle/lineWidth (colours and line thickness) set beforehand. fillText writes text on the letters' baseline. Transforms (translate, rotate, scale: move, turn, resize) change the coordinate system and stack, so wrap them in save() (store the state) and restore() (bring it back). drawImage pastes a picture or another canvas, once the picture has loaded. On a retina screen, 1 CSS px uses 2 or more screen pixels (this number is devicePixelRatio, dpr), so the canvas pixels are stretched and look blurry. The fix: canvas.width = 300 * dpr, CSS stays 300 px, then setTransform(dpr, 0, 0, dpr, 0, 0) to enlarge the drawing dpr times.

⚡ Get the brush first

Write:

const canvas = document.getElementById('print');
const ctx = canvas.getContext('2d');

Meaning: <canvas width="300" height="300"> is a blank sheet of pixels (dots of colour), and the first line gets it by its id. getContext('2d') gives you the brush, called the context. You call every drawing command through ctx. Each point is written (x, y): point (0, 0) is the top-left corner, x grows to the right and y grows downwards.

⚡ A box starts at its top-left corner

Write:

ctx.fillStyle = SHIRT;
ctx.fillRect(0, 0, 300, 300);
Guess first: in fillRect(10, 20, 100, 50), what are 100 and 50?

The box's width and height, not its bottom-right corner. (10, 20) is the box's top-left corner, not its centre.

Meaning: fillRect(x, y, width, height) fills a box. You set its colour with fillStyle before you draw the box. SHIRT is a constant that holds black, the background of the t-shirt print we are drawing.

⚡ Paths and radians

Write:

ctx.beginPath();
ctx.arc(200, 160, 24, -Math.PI / 2, Math.PI / 2);
ctx.stroke();
Guess first: the last two numbers of arc are the start and end angles. Why not just write arc(200, 160, 24, 0, 180)?

Because canvas angles are written in radians, not degrees. Half a turn is Math.PI radians, about 3.14. So 180 radians is far more than one full turn, and you get a whole circle.

Meaning: A path is a chain of lines that stays invisible until you call fill() (fill it) or stroke() (draw its outline). beginPath() opens a new path, then arc adds an arc (a piece of a circle) centred at (200, 160) with a radius of 24. From -Math.PI / 2 (up) to Math.PI / 2 (down), clockwise, the arc is the right half of a circle: the cup's handle in the t-shirt print.

⚡ Wrap transforms in save and restore

Write:

ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.scale(1, 0.6);
// ...draw the bean at (0, 0)
ctx.restore();

Meaning: This code draws one coffee bean in the t-shirt print. translate, rotate and scale are called transforms: they move, turn and resize the paper (the canvas's coordinate system). So a circle drawn at (0, 0) appears at (x, y), tilted and squashed. save() stores the paper's state, and restore() brings it back. Transforms stack, so without save()/restore(), the second bean is drawn on paper still moved by the first bean, and it lands outside the canvas, with no error.

What you will learn