All examples By author By category About

nitaku

ID-based force layout

d3.js's force layout works fine with index-based node references in links, since it substitutes them internally with the corresponding node from the nodes array. This simple approach is effective when we can refer to nodes by their index in the nodes array. But what if we have an ID for each node and we want links to refer to those IDs?

If we resolve the IDs into nodes before passing them to d3.js's force layout, everything works as expected. This example illustrates the technique by repurposing another example by Mike Bostock.

Each node is given a string ID (a letter), and each link uses them to refer to the nodes it connects to. The code iterates through the links array to resolve the references.

Like in the original example, nodes are placed in precomputed positions, are made draggable, and are made fixed (i.e. not subject to the force) when dragged.