Drag Shapes on HTML Canvas with Pointer Events

To drag a shape on Canvas, Canvas does not move an HTML element for you. Track the pointer, test whether it started inside the shape, update the shape coordinates during pointermove, then clear and redraw the Canvas.

Drag the rectangle Top ↑

Draggable rectangle on Canvas.

Drag the rectangle with a mouse, touch or pen.

Core Pointer Events drag logic Top ↑

canvas.addEventListener('pointerdown', (event) => {
  const p = getCanvasPoint(event);
  if (insideRectangle(p)) {
    dragging = true;
    canvas.setPointerCapture(event.pointerId);
  }
});

canvas.addEventListener('pointermove', (event) => {
  if (!dragging) return;
  const p = getCanvasPoint(event);
  box.x = p.x - dragOffsetX;
  box.y = p.y - dragOffsetY;
  redraw();
});

canvas.addEventListener('pointerup', () => {
  dragging = false;
});

Hit testing Top ↑

For a rectangle, hit testing is a simple bounds check. For complex paths, consider isPointInPath() or maintain your own object geometry.

Why pointer capture helps Top ↑

Without pointer capture, a fast drag may stop when the pointer leaves the Canvas. Capturing the active pointer keeps the drag interaction connected until release or cancellation.

Provide a non-drag alternative Top ↑

Dragging is not enough for an essential control. Provide keyboard-operable buttons, fields, or another semantic HTML method to change the same value or position.

Frequently asked questions Top ↑

Do I need jQuery to drag Canvas shapes? Top ↑

No. Pointer Events provide a native mouse, touch and pen solution.

Why must the Canvas be redrawn while dragging? Top ↑

Canvas is immediate-mode graphics; changing your object coordinates does not move pixels already painted.

What does setPointerCapture() do? Top ↑

It keeps pointer events directed to the Canvas during an active drag even when the pointer moves outside it.

How do I stop a shape leaving the Canvas? Top ↑

Clamp the updated x and y values to the Canvas bounds, accounting for the shape width and height.

How can keyboard users move the same shape? Top ↑

Provide buttons or other focusable HTML controls that update the same object coordinates and redraw the Canvas.

Canvas Pointer Events | 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