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');
widthandheightare the number of pixels in the drawing. Without those attributes, a canvas is 300 × 150.- The first line gets the canvas element by its id.
getContext('2d')returns the context: the brush that holds every 2D drawing command, stored inctx. You call all of those commands throughctx, not throughcanvas.
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);
fillRect(x, y, width, height)fills a box. (x, y) is its top-left corner, not its centre. The fabric starts at (0, 0), 300 wide and 300 tall.fillStyle(fill colour),strokeStyle(line colour) andlineWidth(line thickness) are set before the drawing command. They apply to everything drawn after them, until you change them.- A path is a chain of lines that stays invisible until you call
fill()orstroke().beginPath()opens a new path and throws the old one away. moveTo(x, y)moves the pen (the point where the next line starts) without drawing.lineTo(x, y)draws a line from where the pen is to the point (x, y).closePath()draws a line back to the path's starting point.fill()fills the inside of the path, andstroke()draws its outline. The cup's 8 px outline is centred on the path: 4 px inside and 4 px outside.arc(x, y, radius, startAngle, endAngle)makes an arc (a piece of a circle) with its centre at (x, y). The arc of the cup's handle runs from-Math.PI / 2(up) toMath.PI / 2(down), clockwise through 3 o'clock: the right half of a circle. A canvas has nocircle(). You write a full circle asarc(x, y, r, 0, Math.PI * 2).fillText(text, x, y)writes text. y is the letters' baseline (the line the letters stand on), not their top edge.textAlign = 'center'makes x the middle of the text.
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);
translate(move),rotate(turn) andscale(resize) change the coordinate system, and they stack: the second transform is applied on top of the result of the first.save()puts the transform, colours,lineWidth,fontand other settings on a stack.restore()brings back the settings that were saved last.- Without
save()/restore(), the first bean's transforms are still active.bean(238, ...)then moves paper that was already moved to (62, 266), turned -0.5 and squashed. The second bean lands around (347, 292), outside the 300 × 300 canvas. There is no error. You just don't see the second bean. - A tilted oval bean can also be drawn with one call, without transforms:
ctx.ellipse(x, y, 12, 7.2, angle, 0, Math.PI * 2). The numbers 12 and 7.2 (12 × 0.6) are its radii, andangleis how far it turns.
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
Math.roundrounds the result, because the DPR can be a fraction (1.25 or 1.5 on Windows laptops), whilewidthhas to be a whole number.- Changing
canvas.widthwipes the drawing and resets the context (transform, colours, font). So the order is: size first, thensetTransform, then draw. setTransform(dpr, 0, 0, dpr, 0, 0)enlarges everything you draw by the DPR and replaces the old transform.scale(dpr, dpr)stacks: called twice at DPR 2 (for example, on every window resize), the scale becomes 4 times and the drawing grows.- The DPR can change while the page is open, for example when the user zooms or moves the window to another monitor. So wrap the code above in one function. At the end of that function, add a
changelistener onmatchMedia('(resolution: ' + dpr + 'dppx)')that calls the function again, so each new DPR gets a new query.
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);
- The 5-argument form:
drawImage(source, x, y, width, height). The 9-argument form: after the source, the first four numbers cut a box out of the source (in source pixels, so they are multiplied bydpr), and the next four are the box it lands in. - A picture from a file takes time to load. The browser runs
onloadonce the picture has loaded. AdrawImagecalled before then draws nothing, with no error.
⚠️ Why doesn't the print come out the way the code says?
- Forgetting
beginPath(). WithoutbeginPath()in step 5, the handle's path is still there. The saucer'sstroke()draws the handle again too, withlineWidth10, so the handle gets thicker. - Setting the colour after the shape.
fillRectand thenfillStyle = '#3498db'draws the box in the colour that was set before. Set the colour first. - Degrees, not radians.
arc(200, 160, 24, 0, 180)doesn't give half a circle. The canvas reads 180 as 180 radians, far more than one full turn, so you get a whole circle. - Sizing the canvas only with CSS.
width: 100%in CSS only stretches the same 300 pixels, so the drawing is blurry. If the ratio of width to height changes too, circles turn oval.
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.