Workshop › Memory › Step 14 of 25
On a click, we turn the click into canvas pixels, find the card there, and turn it face up. The loop draws the change.
```js
canvas.addEventListener('click', (event) => {
// The canvas may be displayed at a different size than its own pixels, so scale the click.
const rect = canvas.getBoundingClientRect()
const x = (event.clientX - rect.left) * (canvas.width / rect.width)
const y = (event.clientY - rect.top) * (canvas.height / rect.height)
const card = cardAt(x, y)
if (card) card.faceUp = true
})
```addEventListener('click', ...) runs the function on every click on the canvas; event carries the mouse position.getBoundingClientRect() gives where the canvas is and how big it is shown. Subtract its left/top, then scale by
canvas.width / rect.width.if (card) card.faceUp = true: a click in a gap finds no card and does nothing. The loop shows the change.Above function draw, write the click listener, then an empty line. Run and click a few cards.
Skills: Keyboard and mouse input
← Which card is at a point? One place for the rules →