Workshop › Conway's Game of Life › Step 22 of 32
To paint with the mouse or a finger we need the pointer's place in canvas pixels. The browser gives it relative to the page, and the canvas may be shown larger or smaller than 480 pixels, so we convert.
```js
function toCanvas(event) {
const rect = canvas.getBoundingClientRect()
return {
x: ((event.clientX - rect.left) * canvas.width) / rect.width,
y: ((event.clientY - rect.top) * canvas.height) / rect.height,
}
}
```getBoundingClientRect() gives the canvas's box on the screen: left, top, width, height.event.clientX - rect.left is how far the pointer is from the canvas's left edge, in screen pixels.* canvas.width / rect.width turns screen pixels into canvas pixels (halves them if the canvas is shown twice as
big).{ x, y }.Write toCanvas above function update() {, with an empty line between them.
Skills: Keyboard and mouse input
← Clear and shuffle Which cell? →