Canvas Pointer Events in JavaScript: Get X and Y Coordinates

Use Pointer Events to read Canvas input from a mouse, touch screen, or pen with one JavaScript event model. The most common events for Canvas interaction are pointerdown, pointermove, pointerup, pointerenter, and pointerleave.

Live Canvas pointer coordinates Top ↑

Canvas pointer coordinate demo.

Move or press a pointer inside the Canvas.

JavaScript for Canvas X/Y coordinates Top ↑

const canvas = document.getElementById('pointer_canvas');

function getCanvasPoint(event) {
  const rect = canvas.getBoundingClientRect();
  return {
    x: (event.clientX - rect.left) * canvas.width / rect.width,
    y: (event.clientY - rect.top) * canvas.height / rect.height
  };
}

canvas.addEventListener('pointermove', (event) => {
  const point = getCanvasPoint(event);
  console.log(point.x, point.y, event.pointerType);
});

Why coordinate scaling matters Top ↑

A Canvas has bitmap dimensions (width/height attributes) and may also have a different CSS display size. getBoundingClientRect() reports the displayed rectangle, so scale the pointer coordinates when those sizes differ.

Pointer capture for dragging Top ↑

For drag interactions, call setPointerCapture(event.pointerId) after pointerdown so movement can continue even when the pointer temporarily leaves the Canvas. See the dragging tutorial.

What about mouse events and jQuery? Top ↑

Mouse events remain useful for mouse-only interfaces, and the older jQuery Canvas event example is preserved for legacy code. Pointer Events are more flexible for new work.

Frequently asked questions Top ↑

Which Canvas event gives mouse and touch coordinates? Top ↑

Pointer Events are a unified option. pointermove and pointerdown expose clientX and clientY for mouse, touch and pen pointers.

Why use getBoundingClientRect()? Top ↑

It gives the Canvas position and rendered size in viewport coordinates so pointer positions can be converted correctly.

What is pointerType? Top ↑

It reports the pointer source, commonly mouse, pen or touch.

Why use setPointerCapture()? Top ↑

It keeps subsequent pointer events associated with the element during dragging, even if the pointer moves outside its bounds.

Should important controls exist only inside Canvas? Top ↑

No. Provide semantic HTML controls or equivalent accessible interaction for essential tasks.

Drag Canvas shapes | Legacy jQuery events | JavaScript events | Canvas tutorial





plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer