Force Layout

<GraphCanvas forceLayout /> runs a force-directed simulation that pushes connected nodes apart, attracts linked nodes together, and pulls everything toward the centre — the standard "spring-and-charge" layout you see in most graph visualisations.

<GraphCanvas data={graph} forceLayout />                              // defaults
<GraphCanvas data={graph} forceLayout={{ engine: "webgpu" }} />       // explicit backend
<GraphCanvas data={graph} forceLayout={{ alphaDecay: 0.02 }} />       // slower convergence

Choosing a backend

forceLayout runs on one of two compute backends. Pick by engine field:

engine Node count sweet spot Browser support Notes
"d3" (default) < 5 000 Every modern browser CPU d3-force-3d.
"webgpu" 5 000 – 1 000 000 Chrome 113+, Edge 113+ WebGPU compute shaders. Falls back to "d3" with a dev-mode warning if navigator.gpu is unavailable, so it is safe to request unconditionally.
"auto" any All Picks "webgpu" when supported, otherwise "d3".

The default is the CPU backend even on machines that could run the GPU one. That is a choice about how the layout looks, not about what the machine can do: d3-force-3d settles into a graph that reads better, and the two backends do not converge to the same shape. While "auto" was the default, the same data settled differently depending on whether the viewer's browser exposed navigator.gpu — a screenshot from one machine did not match another, and a layout tuned on a GPU machine came out wrong for half the audience.

So reach for "webgpu" when the node count is the problem, not when you want a better picture. Under about 5 000 nodes there is nothing to gain.

The default was "auto". If your application relied on getting the WebGPU backend without asking for it, set forceLayout={{ engine: "auto" }} to restore the old behaviour — and expect the layout to differ from the 0.7.0 default.

The WebGPU backend is also no longer in the default download. GraphCanvas fetches it the first time a canvas asks for it, which took 43 KiB gzip off the package entry. You do not have to do anything to get this: engine: "webgpu" and engine: "auto" work exactly as before, and the first layout on a canvas that asks for WebGPU starts after one extra network round trip (or instantly, once your bundler has it in the same chunk graph). What did move is the controller classes — see below.

Removed in Phase 6: the WebGL2-GPU backend (engine: "gpu") is no longer selectable via this prop. The underlying GPUForceLayoutController class remains available from @kineviz/gl/layout-gpu — hosts that need it can pre-construct one and pass it via the layoutController prop.

Tuning the simulation

The remaining fields tune the physics. They're shared across all backends; the engine normalises them internally so the same values produce visually comparable layouts.

alpha number
0.6
Initial simulation energy. Higher = more dramatic motion at start.
alphaDecay number
0.1
Per-tick alpha decay rate. Lower = layout converges more slowly but reaches a tighter resting state.
charge number
-0.01
Inter-node repulsion (negative = repel). More negative pushes nodes further apart.
collision number
0.15
Node-node collision force preventing overlap.
friction numberVelocity damping (d3-force friction alias).
gravity number
0.1
Centring force strength. Higher = nodes pulled tighter toward origin.
linkDistance number
0.5
Target edge length.
linkStrength number
1.0
Edge spring strength.

For backend-specific knobs (octree depth, LBVH levels, etc.) construct a controller directly and pass it via layoutController instead of forceLayout.

When to use what

  • forceLayout (this page): the easy declarative path. One prop, defaults work, engine handles the lifecycle.

  • layoutController: hand a pre-constructed GPUForceLayoutController / WebGPUForceLayoutController (or any LayoutControllerInterface implementation) when you need fine control — running the simulation in a worker, sharing it between canvases, feeding custom positions. Import those two from @kineviz/gl/layout-gpu:

    import { WebGPUForceLayoutController } from "@kineviz/gl/layout-gpu";
    

    :::caution Changed in 0.7.0 They used to be exported from @kineviz/gl itself. A static export there is an eager one, so every application downloaded both GPU layout backends whether or not it used them. Change the import path; the classes are unchanged. :::

  • layout.* namespace (/docs/api/layout): one-shot geometric layouts (circle, grid, spiral, scatter) that compute positions once and stop. No simulation.

forceLayout and layoutController are mutually exclusive — layoutController wins when both are set.

Registering your own layout

A one-shot layout is a pure function of a context: the nodes taking part, their current positions, and all the edges. Register one and it is applied exactly like a built-in — recorded in undo history, animated by the position tween, and bracketed by layout:start / layout:end.

import type { LayoutContext, Vec3 } from '@kineviz/gl';

const off = api.layout.register('acme:rack', (ctx: LayoutContext, opts?: { rows?: number }) => {
  const positions = new Map<string, Vec3>();
  ctx.nodes.forEach((n, i) => {
    positions.set(n.id, [i % (opts?.rows ?? 8), Math.floor(i / (opts?.rows ?? 8)), 0]);
  });
  return { positions };
});

await api.layout.applyByName('acme:rack', undefined, { rows: 4 });
off();                                   // remove the registration
interface LayoutContext {
  nodes: ReadonlyArray<NodeData>;              // the nodes taking part
  positions: ReadonlyMap<string, Vec3>;        // current positions of every node
  edges: ReadonlyArray<EdgeData>;              // all edges, for structure-aware layouts
}

Rules worth knowing:

  • An extension name must be "<pack>:<name>", and must not collide with a built-in or an existing registration. Pass { replace: true } to replace another extension. A bad name throws.
  • Registrations are per engine instance — registering on one canvas does not affect another.
  • api.layout.has(name) and api.layout.list() report built-ins and registrations together.
  • applyByName with an unregistered name throws, and the error lists the valid names. (It used to return silently, which hid typos — see Upgrading.)
  • options is forwarded to registered layouts as-is. The built-in names ignore it; call their typed method to pass options to those.

Two flyable layouts ship this way and are registered with one call — see Cinematics.

See also