Workshop › Tower Defense › Step 13 of 42
A click gives a position in screen pixels, but the game thinks in canvas pixels, and they are not the same:
the page scales the canvas to fit the screen. tileAt converts, then finds the tile.
```js
// Mouse and touch positions are in screen pixels; the canvas may be drawn smaller or bigger than its own pixels.
function tileAt(event) {
const rect = canvas.getBoundingClientRect()
const x = ((event.clientX - rect.left) * canvas.width) / rect.width
const y = ((event.clientY - rect.top) * canvas.height) / rect.height
return { x, y, col: Math.floor(x / TILE), row: Math.floor((y - TOP) / TILE) }
}
```getBoundingClientRect() says where the canvas is on the screen and how big it is shown.rect.left makes the position relative to the canvas; multiplying by canvas.width / rect.width undoes
the scaling.Math.floor(x / TILE) is the column; the row counts from TOP, so a click in the top strip gives row -1.Under pointAt, after an empty line, write the comment and tileAt.
Skills: Keyboard and mouse input