Drawing on the Canvas
Set up an HTML canvas, learn why the y axis points down, and draw rectangles, circles and text to build a game scene from simple shapes.
Welcome back!
Step 1 of 11Learn
A rectangle of pixels
Browser games draw on a canvas, an HTML element that gives JavaScript a blank rectangle of pixels. The whole HTML file for a game can be this short:
<!DOCTYPE html>
<html>
<body>
<canvas id="game" width="480" height="320"></canvas>
<script src="game.js"></script>
</body>
</html>In game.js, you grab the canvas and ask it for a drawing context, the object that holds all the drawing commands:
const canvas = document.querySelector("#game");
const ctx = canvas.getContext("2d");The name ctx is a tradition; almost every canvas tutorial uses it. Now you can draw:
ctx.fillStyle = "navy";
ctx.fillRect(0, 0, 480, 320); // background
ctx.fillStyle = "orange";
ctx.fillRect(100, 200, 40, 40); // a player squarefillStyle picks the paint color, and fillRect(x, y, width, height) paints a filled rectangle. The canvas works like a real painting: later shapes are drawn on top of earlier ones. That's why the background goes first. Draw it last and it covers everything.
Notice that the width and height are set as attributes on the canvas element. Setting them with CSS instead stretches the drawing, which makes everything look blurry.
Step 2 of 11Practice · Put in order
Put these canvas setup steps in the right order.
Drag the items, or use the arrow buttons, to put them in order.
- Find the canvas with document.querySelector
- Set fillStyle and call fillRect to draw
- Add a canvas element with a width and height to the HTML
- Get the 2D drawing context with getContext
- Load the script after the canvas
Step 3 of 11Diagram
From HTML to the first rectangle
Tap a shape with to see more.
- <canvas> in the HTML
Gives the page a 480 by 320 pixel drawing area.
- querySelector("#game")
JavaScript grabs the canvas element.
- getContext("2d")
The context
ctxholds every drawing command.- ctx.fillStyle = "navy"
Choose the color first.
- ctx.fillRect(…)
Then paint a rectangle with it.
Step 4 of 11Learn
Why y points down
In math class, the y axis points up: bigger y means higher. On a canvas it's the other way around. The origin (0, 0) is the top-left corner, x grows to the right, and y grows downward.
On a 480 by 320 canvas:
- (0, 0) is the top-left corner.
- (480, 0) is the top-right corner.
- (0, 320) is the bottom-left corner.
- (240, 160) is the center.
This comes from how screens work: they draw rows of pixels starting at the top, like reading a page. It means that in games:
- Moving up means subtracting from y.
- Falling means adding to y.
- The ground is at a large y value, near the canvas height.
Also remember that fillRect(x, y, w, h) uses the top-left corner of the rectangle. A 40-pixel-tall player standing on ground at y = 300 needs y = 260, not 300; otherwise it's drawn below the ground line. To center a square at a point, subtract half its size from both coordinates.
Every new canvas programmer makes a character fly downward when it should jump at least once. If something moves the wrong way vertically, check the sign first.
Step 5 of 11Practice · Work it out
A canvas is 480 pixels wide and 320 tall. A 40 by 40 square should sit exactly centered. What x value should you pass to fillRect?
Step 6 of 11Try the calculator
Center anything on the canvas
fillRect uses the top-left corner, so subtract the object's size from the canvas size and halve it.
- x for fillRect = (W - w) / 2
- 208 px
- y for fillRect = (H - h) / 2
- 144 px
Step 7 of 11Learn
Circles, text and clearing
Rectangles are enough for many games, but you'll want circles for balls and coins, and text for the score.
Circles use a path: you describe a shape, then fill it.
ctx.beginPath();
ctx.arc(240, 160, 15, 0, Math.PI * 2);
ctx.fillStyle = "gold";
ctx.fill();arc(x, y, radius, startAngle, endAngle) describes part of a circle centered at (x, y). Angles are in radians, and a full circle is Math.PI * 2, about 6.28. Unlike fillRect, arc uses the center, not the corner, which matters later for collisions.
Text uses fillText:
ctx.fillStyle = "white";
ctx.font = "20px sans-serif";
ctx.fillText("Score: " + score, 10, 30);The x and y here mark the left end of the text's baseline, the line the letters sit on, so y = 30 keeps a 20-pixel font inside the canvas.
Clearing. A canvas remembers everything you've ever drawn. To animate, you'll erase and redraw the whole scene many times per second. ctx.clearRect(0, 0, canvas.width, canvas.height) wipes everything, or simply paint the background rectangle over the whole canvas, which clears and colors in one step.
Step 8 of 11Practice · Match the pairs
Match each canvas command to what it does.
Tap an answer, then tap the place where it belongs (or drag it there).
- fillRect(x, y, w, h)
- arc(x, y, r, 0, Math.PI * 2)
- fillText(text, x, y)
- clearRect(0, 0, w, h)
- fillStyle = "red"
Step 9 of 11Note
Step 10 of 11Practice · Code challenge
Because fillRect uses the top-left corner, games often need to convert. Write cornerFor(cx, cy, size) that returns an array [x, y]: the top-left corner of a square of the given size whose center is at (cx, cy).
cornerFor(240, 160, 40)cornerFor(50, 50, 10)cornerFor(0, 100, 20)
Step 11 of 11Practice · True or false
On a canvas, an object at y = 50 appears higher on the screen than an object at y = 200.
Lesson complete!