SyntaxStudy
Sign Up
HTML Mouse Interaction on Canvas
HTML Intermediate 5 min read

Mouse Interaction on Canvas

Mouse Events on Canvas

Listen for mouse events on the canvas element and calculate the position relative to the canvas using getBoundingClientRect().

Example
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();
});
Pro Tip

Subtract getBoundingClientRect() from mouse coordinates — event.clientX is relative to the viewport, not the canvas.