Workshop › Connect Four › Step 13 of 38
A click plays the column under the mouse. colAt(event) turns the mouse position into a column number, first converting
screen pixels to canvas pixels, because the page may show the canvas smaller or bigger.
```js
let hoverCol = 3
function colAt(event) {
const rect = canvas.getBoundingClientRect()
const x = ((event.clientX - rect.left) * canvas.width) / rect.width
return Math.min(COLS - 1, Math.max(0, Math.floor(x / CELL)))
}
canvas.addEventListener('pointerdown', (event) => {
hoverCol = colAt(event)
play(hoverCol)
})
```hoverCol is the chosen column.getBoundingClientRect() gives where the canvas is on the screen (left) and how wide it is shown (width);
event.clientX is the mouse position. Together they give x in canvas pixels.Math.floor(x / CELL) is the column; Math.max(0, ...) and Math.min(COLS - 1, ...) keep it between 0 and 6.addEventListener('pointerdown', ...) runs the arrow function on every click.let turn write let hoverCol = 3.function disc( write colAt and the pointerdown listener, followed by an empty line.Skills: Keyboard and mouse input
← Taking turns The next disc →