Workshop › Hangman › Step 31 of 36
Where each key goes
What we are doing
A phone opens no keyboard for a canvas, so the game will draw its own: 26 keys in rows of 9. First, keyRect(i)
works out where key number i goes.
```js
const KEY_W = 48
const KEY_H = 34
const KEYS_Y = 360
function keyRect(i) {
const row = Math.floor(i / 9)
return { x: 8 + (i % 9) * (KEY_W + 4), y: KEYS_Y + row * (KEY_H + 6) }
}
```
What it means
- A key is 48×34 pixels; the keyboard starts at y = 360.
Math.floor(i / 9) is the row: keys 0–8 are row 0, 9–17 row 1, 18–25 row 2.
i % 9 is the remainder after dividing by 9: the place in the row.
- Each key is 4 pixels further than the width (a gap), each row 6 pixels further than the height.
return { x, y } gives back an object: the key's top-left corner.
Your turn
- Under
const MAX_WRONG = 6 write the three key sizes.
- Above
canvas.addEventListener('pointerdown', ...), write keyRect and leave an empty line. Press Run.
Skills: Drawing on a canvas
← Remember the best streak Draw the keys →
All steps
- A list of secret words
- The canvas and the pen
- Paint the paper
- A function that draws
- Pick a random word
- Write the word
- Hide it behind blanks
- Remember the guesses
- Draw again and again
- A guess
- Guess with the keyboard
- Only letters count
- Count the misses
- The same letter twice is free
- Six misses at most
- Show the misses
- List the wrong letters
- Draw a line
- The gallows
- The first miss: a head
- Body, arms and legs
- The parts in a list
- Losing
- Winning
- Show the word you missed
- The end message
- Play again
- Never the same word twice
- A winning streak
- Remember the best streak
- Where each key goes
- Draw the keys
- Center the last row
- Keys that remember
- Tap a key
- Build it yourself: a hint button