Skip to content

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.

Templates:
Input Node
Standard Node
Output Node
Existing Node
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

MethodDescriptionSignature
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

  1. Attach draggable="true" and @dragstart to your sidebar elements to store the node type in dataTransfer.
  2. Enable @dragover on the container to allow dropping.
  3. In the @drop handler, calculate the relative offset by subtracting the container's getBoundingClientRect() from clientX/Y.
  4. Pass the relative coordinates to flowInstance.screenToCanvas.
  5. Push a new entry into your nodes array with the resulting position.

Released under the MIT License.