
For a pointer event, clientX and clientY are measured from the browser window, while getBoundingClientRect() gives the canvas’s position in that same coordinate system. Subtract the rectangle’s left and top edges to get coordinates relative to the canvas’s displayed area.
const canvas = document.querySelector("canvas");
canvas.addEventListener("pointerdown", event => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
console.log({ x, y });
});
This gives coordinates in CSS pixels. Keep the canvas free of padding and borders when possible; otherwise, the rectangle includes the border box, and you’ll need to subtract the border width to measure from the drawable content edge.
Now loading...
Account for scaling and device pixel ratios
The canvas has two sizes: its CSS size on the page and its intrinsic size, given by canvas.width and canvas.height. When they differ, scale the pointer coordinates by the ratio of intrinsic dimensions to the displayed rectangle. This also handles a canvas resized by CSS.
function canvasPoint(canvas, event) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * canvas.width / rect.width,
y: (event.clientY - rect.top) * canvas.height / rect.height
};
}
For a high-density display, allocate a backing store at the device pixel ratio while keeping the displayed size in CSS pixels. Scale the drawing context so drawing commands can continue to use CSS-pixel coordinates:
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
function resizeCanvas() {
const rect = canvas.getBoundingClientRect();
const ratio = window.devicePixelRatio || 1;
canvas.width = Math.round(rect.width * ratio);
canvas.height = Math.round(rect.height * ratio);
context.setTransform(ratio, 0, 0, ratio, 0, 0);
}
resizeCanvas();
With that setup, convert events to CSS-pixel coordinates for drawing operations, or to backing-store coordinates when an API expects the canvas’s intrinsic pixel grid. Do not multiply by the device pixel ratio twice: the rectangle-to-intrinsic-size ratio already includes it.
canvas.addEventListener("pointerdown", event => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
context.fillRect(x, y, 4, 4);
});
Track pointer movement and verify the coordinates
Use pointermove to observe the coordinates continuously. The following reports CSS-pixel positions, which match the coordinate system used by the scaled drawing context in the previous example:
const position = document.querySelector("#position");
canvas.addEventListener("pointermove", event => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
position.textContent = "x: " + x.toFixed(1) + ", y: " + y.toFixed(1);
});
Move the pointer to the canvas’s upper-left corner and check that the readout is near x: 0, y: 0. At the lower-right corner, it should approach the displayed width and height. Small discrepancies at the edges are normal: pointer coordinates can land on fractional CSS pixels, and the final pixel begins just before the rectangle’s far edge.
For dragging, capture the pointer on press. Movement events then continue to reach the canvas even if the pointer leaves its bounds; coordinates outside the canvas are valid and will be negative or greater than its displayed dimensions.
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
position.textContent = "x: " + x.toFixed(1) + ", y: " + y.toFixed(1);
});
Source: https://www.jsfaq.com/how-to-detect-mouse-coordinates-on-canvas-in-javascript/