Workshop › Candy Crush-style Match 3 › Step 7 of 29
A move starts by clicking a gem. cellAt turns the click's position into a row and a column (or null off the
board), and the click remembers that cell in selected.
```js
let selected
function cellAt(event) {
const rect = canvas.getBoundingClientRect()
const x = ((event.clientX - rect.left) * canvas.width) / rect.width - LEFT
const y = ((event.clientY - rect.top) * canvas.height) / rect.height - TOP
const r = Math.floor(y / SIZE)
const c = Math.floor(x / SIZE)
return r >= 0 && r < N && c >= 0 && c < N ? { r, c } : null
}
canvas.addEventListener('pointerdown', (event) => {
const cell = cellAt(event)
if (!cell) return
selected = cell
})
```getBoundingClientRect() gives its place and size on
screen, so the click position is turned into canvas pixels, then made relative to the grid's corner.SIZE and rounding down gives the row and column.null. { r, c } is short for { r: r, c: c }.pointerdown fires when a mouse button or a finger goes down on the canvas.let board write let selected.function draw() { write cellAt and the listener.Skills: Keyboard and mouse input
← Start without matches Show the selection →