Workshop › Minesweeper › Step 12 of 26
A click opens the cell under the pointer. cellAt(event) scales the click into canvas pixels and divides by CELL to
find the column and row; clicks on the top strip give undefined.
```js
function cellAt(event) {
// The canvas may be displayed at a different size than its own pixels, so scale the pointer.
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 col = Math.floor(x / CELL)
const row = Math.floor((y - TOP) / CELL)
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) return undefined
return grid[row][col]
}
canvas.addEventListener('click', (event) => {
const cell = cellAt(event)
if (cell) reveal(cell)
})
```getBoundingClientRect() gives the canvas's place and size on the screen; the pointer is scaled into canvas pixels.CELL, rounded down, gives the column and row.undefined, which if (cell) treats as "no cell".addEventListener('click', ...) runs the function on every click, with the click's details in event.Above function draw() {, write cellAt and the click listener, with an empty line after each. Press Run and click.
Skills: Keyboard and mouse input
← Coloured numbers Stepping on a mine →