HTML5 Canvas

Drag and drop on a Canvas scene

A tree-decorating scene is a useful way to learn pointer input: select an ornament, drag it and release it at a new position. Keep each ornament’s position and bounds in the model so the drawing routine stays simple.

Convert pointer coordinates from the canvas’s CSS box into its drawing-buffer coordinates. Remember the offset between the click and the ornament’s origin, otherwise the ornament jumps to put its corner under the pointer.

Capture the active pointer while dragging, and handle cancellation as well as release. Add an HTML reset button and a keyboard method for selecting and moving ornaments so dragging is not the only usable interaction.

Try the idea

const rect = canvas.getBoundingClientRect();
const x = (event.clientX - rect.left) * canvas.width / rect.width;
const y = (event.clientY - rect.top) * canvas.height / rect.height;
selected.x = x - grabOffsetX;
selected.y = y - grabOffsetY;