Drag & Drop
A common requirement for visual editors is allowing users to drag node templates from a sidebar and drop them onto the canvas. Flow facilitates this by providing the screenToCanvas utility, which handles all coordinate transformations including zoom and pan offsets.
Interactive Drag & Drop Demo
Drag any node block from the sidebar on the left and drop it into the gray canvas area on the right.
Native HTML5 Drag & Drop
Implementation Details
The core of the drag-and-drop workflow is the screenToCanvas method. Standard browser mouse coordinates (clientX, clientY) are relative to the browser window, whereas the items inside Flow are offset by the current pan position and compressed/expanded by the current zoom level.
Transformation Utility
| Method | Description | Signature |
|---|---|---|
screenToCanvas(x, y) | Takes coordinates relative to the Flow container (px) and returns the corresponding coordinates within the graph's coordinate system. | (x: number, y: number) => { x: number, y: number } |
Step-by-Step Logic
- Attach
draggable="true"and@dragstartto your sidebar elements to store the node type indataTransfer. - Enable
@dragoveron the container to allow dropping. - In the
@drophandler, calculate the relative offset by subtracting the container'sgetBoundingClientRect()fromclientX/Y. - Pass the relative coordinates to
flowInstance.screenToCanvas. - Push a new entry into your
nodesarray with the resulting position.