Skip to main content
100%

Sticky Force Layout

✓ Published0🌍 Public
Mmbostock
Last edited Feb 9, 2016
Created on Sep 19, 2012

D3’s force layout runs with 13 nodes and 18 links from `graph.json`, rendered as SVG circles and lines. Dragging a node during the layout’s drag behavior sets its `fixed` property to true on `dragstart`, preventing the simulation from moving it afterward; double-clicking clears that flag. The force layout automatically resumes on `dragmove`, so the repositioned node continues to affect neighbors. Fixed nodes turn red, and the code uses `d3.layout.force`, the drag behavior, and explicit `tick` handlers to update positions.

AI-generated description

This example demonstrates how to prevent D3’s force layout from moving nodes that have been repositioned by the user. When the force layout’s drag behavior dispatches a dragstart event, the fixed property of the dragged node is set to true. This prevents the force layout from subsequently changing the position of the node (due to forces). Double-click to release a node.

Internally, the force layout uses three bits to control whether a node is fixed. The first bit can be set externally, as in this example. The second and third bits are set on mouseover and mousedown, respectively, so that nodes are fixed temporarily during dragging. Although the second and third bits are automatically cleared when dragging ends, the first bit stays true in this example, and thus nodes remain fixed after dragging.

Also note that the force layout resumes automatically on dragmove. This ensures that other nodes in the graph respond naturally to the dragged node’s movement.

gpl-3.0 Licensed

Similar vizzes