Canvas Drag and Drop with JavaScript and Konva
The Canvas API does not provide drag and drop for drawn shapes. A raw Canvas application must implement four parts:
- Store each shape and its position.
- Detect the shape under the pointer.
- Convert browser coordinates to canvas coordinates.
- Update the shape and redraw the scene during a drag.
Pointer events support a mouse, pen, and touch input through one event model.
Call setPointerCapture() after pointerdown in a raw Canvas implementation.
The capture keeps move events active outside the canvas.
Drag a Konva node
Konva implements hit detection and pointer tracking. Set draggable on a node.
Then store its final position in application state.
Konva changes the node position during a drag. The example also writes that position to React state. This state keeps the application model synchronized.
For large scenes, do not update unrelated React state on each dragmove event.
Update the Konva node during the drag. Save the final application state on
dragend when other components do not need live coordinates.
Canvas shapes are not keyboard controls. Provide an HTML control for each essential drag action. The control can move the same shape in fixed steps.
See the drag and drop guide for Vanilla, React, Vue, Svelte, and Angular examples.