Mouse Events on Canvas
Listen for mouse events on the canvas element and calculate the position relative to the canvas using getBoundingClientRect().
Listen for mouse events on the canvas element and calculate the position relative to the canvas using getBoundingClientRect().
const ctx = canvas.getContext("2d");
let drawing = false;
canvas.addEventListener("mousedown", () => drawing = true);
canvas.addEventListener("mouseup", () => drawing = false);
canvas.addEventListener("mousemove", (e) => {
if (!drawing) return;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ctx.fillStyle = "#007bff";
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
});
Subtract getBoundingClientRect() from mouse coordinates — event.clientX is relative to the viewport, not the canvas.