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 with a mouse, touch or pen.
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;
});
For a rectangle, hit testing is a simple bounds check. For complex paths, consider isPointInPath() or maintain your own object geometry.
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.
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.
No. Pointer Events provide a native mouse, touch and pen solution.
Canvas is immediate-mode graphics; changing your object coordinates does not move pixels already painted.
It keeps pointer events directed to the Canvas during an active drag even when the pointer moves outside it.
Clamp the updated x and y values to the Canvas bounds, accounting for the shape width and height.
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.