Workshop › Chess › Step 12 of 48
To pick up a piece we must turn a click into a square. The listener converts the pointer position into canvas pixels,
removes the margins, divides by the square size and rounds down. clickSquare remembers the square in selected.
```js
let selected // the square of the piece you picked up, or null
selected = null
function clickSquare(r, c) {
selected = [r, c]
}
canvas.addEventListener('pointerdown', (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 / SQ)
const c = Math.floor(x / SQ)
if (inside(r, c)) clickSquare(r, c)
})
```selected is null ("nothing") until a square is clicked.pointerdown fires when a mouse button or a finger goes down on the canvas.getBoundingClientRect() is where the canvas is on the screen and how big it is shown; subtracting its left and
scaling by canvas.width / rect.width gives canvas pixels even if the canvas is shown smaller.LEFT/TOP, divided by SQ and rounded down with Math.floor, the pixel becomes a row and column.let board ... write let selected ...; in reset, under the board = ... line write selected = null.function draw() { write clickSquare and the listener.Skills: Keyboard and mouse input
← The king steps too Light up the selected square →