Skip to content

Camera and 3D

The default orthographic camera makes the graph behave as a native 2D surface. The perspective camera is available on demand for structures where depth carries meaning. Both modes use the same node and edge contract.

graph.setMode("3d");
graph.fitView();

setMode() replaces the camera and controls and fits the current graph. Data, selection and IDs do not change. getMode() returns the active mode.

fitView() fits the camera to every node. Pass { nodeIds } to frame a subset, for example a highlighted path:

graph.fitView({ nodeIds: ["person:ada", "place:london"] });

Unknown IDs are ignored; an empty or unmatched list frames every node. In 2D it also resets wheel zoom. In 3D it returns to the front view and keeps every node, glow halos included, on the canvas.

flyTo({ nodeIds }) animates the camera to the framing fitView({ nodeIds }) would give, with an ease-in-out, and returns a promise:

const arrived = await graph.flyTo({ nodeIds: cluster, durationMs: 1200, distanceScale: 1.4 });

In 3D the camera and the orbit target move together and the camera keeps its current view direction instead of returning to the front view, at the fitted distance times distanceScale (default 1; above 1 leaves air around the nodes). In 2D it pans and zooms. durationMs defaults to 1200; 0 jumps, and so does every flight when the person has prefers-reduced-motion: reduce set.

The promise resolves true on arrival and false when the flight is cancelled: by pointer, wheel or key input on the canvas, another flyTo, fitView, setData (unless it is called with { fit: false }, which leaves the camera and a running flight alone), setMode, a 2D resize (which refits) or destroy(). A cancelled flight leaves the camera where it was. Unknown IDs are ignored; when none match, it resolves false without moving. Each flight frame renders once and calls onViewChange listeners, so labels follow; in 3D it does not repack node or edge instances. After arrival the far plane still holds the whole graph, so the rest of it stays visible around the framed nodes.

flyTo works with the auto-orbit: the orbit keeps turning the camera during the flight and carries on around the new target afterwards. Input still cancels the flight and pauses the orbit as usual. An ambient tour can fly on to the next cluster every few seconds:

async function tour(clusters: string[][]) {
for (const nodeIds of clusters) {
if (!(await graph.flyTo({ nodeIds, distanceScale: 1.5 }))) return; // the person took over
await new Promise((resolve) => setTimeout(resolve, 8000));
}
}
const view = graph.getCameraState();
localStorage.setItem("view", JSON.stringify(view));
// later, on a graph in the same mode with its data loaded
const saved = localStorage.getItem("view");
if (saved) graph.setCameraState(JSON.parse(saved));

getCameraState() returns plain JSON. In 2D it is the centre and visibleHeight, the world height the canvas shows from top to bottom with the current zoom applied. In 3D it is the camera position and the target it looks at and orbits. Both carry their mode.

setCameraState() moves the camera there at once, without fitting or animating, and cancels a running flyTo. It throws, and leaves the camera where it is, for a state of the other mode (call setMode() first) and for a missing or non-finite number. Auto-orbit and flyTo carry on from the restored pose, and fitView() still frames the graph.

A 2D state keeps its height and takes the width from the canvas, so a view saved on one canvas size fits another. A 3D state sets the clip planes from the pose, so the whole graph stays in view even from far away; restoring a view that was reached by dollying can differ from the original by a handful of pixels where overlapping nodes sit at nearly the same depth.

Apply a state after the canvas has its size and the data is loaded. A 2D canvas that changes size refits the graph, which replaces the restored view; a resize to the same size does not.

In 2D, drag pans and the wheel or a pinch zooms. One finger pans on touch screens. In 3D, drag rotates, and two fingers zoom and pan.

graph.setNodeDrag({ enabled: true });
const stop = graph.onNodeDrag(({ phase, nodeId, position }) => {
if (phase === "end") savePosition(nodeId, position);
});

Dragging is off by default. With it on, a press on a node followed by a move of more than 5 pixels drags that node. The node keeps the offset at which you grabbed it, so it does not jump to the pointer, and its edges follow on every move. A press that stays under 5 pixels is still a click, and a press on empty space moves the camera as before.

In 2D the node moves in the view plane. In 3D it moves in a plane that faces the camera through the node, so it keeps its distance from the camera and stays under the pointer while you drag.

onNodeDrag reports "start" (with the position the node had), "move" for every step, and "end" on release. Escape, a cancelled pointer or lost pointer capture put the node back and report "cancel" with the position it was restored to. Replacing the data with setData() or switching mode during a drag cancels it. graphraum does not store the new position: write it back to your own data in the "end" listener, because a later setData() uses the positions you pass.

Camera input is paused while a node is dragged, and a running auto-orbit holds still until the node is dropped. Hover highlighting also waits. On touch screens a finger must rest on a node for about a third of a second before it drags, so a swipe that starts on a node still pans the camera. Dragging is not available while the density LOD shows clusters instead of nodes.

if (!matchMedia("(prefers-reduced-motion: reduce)").matches) {
graph.setMode("3d");
graph.setAutoOrbit({ speed: 0.07, resumeAfterMs: 3000 });
}
graph.setAutoOrbit(false);

speed is in radians per second (default 0.07, about 90 seconds per turn; above 0 and at most 2) and holds at any frame rate. Pointer and wheel input on the canvas pause the orbit; it resumes after resumeAfterMs (default 3000) without new input. A drag in progress keeps the camera still even if that delay passes. Pointer input on DOM overlays above the canvas, such as a toolbar or focus cards, does not pause it. The orbit also stops while the tab is hidden or the canvas is scrolled off screen, and resumes when visible again.

While the orbit is active graphraum runs a frame loop instead of rendering only on change. Each active frame rotates the camera, renders once, and calls onViewChange listeners so overlays can follow. It does not repack node or edge instances: in 3D they do not depend on the camera angle, so there is no per-frame CPU repacking or buffer re-upload that grows with graph size. The GPU draw still scales with what is drawn. Paused and disabled orbits run no loop. graphraum does not read prefers-reduced-motion; check it before enabling the orbit, as above. getDiagnostics().autoOrbit reports "off", "active" or "paused".

Large graphs can drop frames while the camera moves. Turn on interaction quality and graphraum draws less while you orbit, pan or zoom, then draws everything again once the camera rests.

const graph = new Graphraum(container, { interactionQuality: { enabled: true } });
graph.setInteractionQuality({ targetFrameMs: 16, idleMs: 250 });
graph.setInteractionQuality({ enabled: false });

It is off by default. While the camera moves, graphraum times each frame. After three frames in a row slower than targetFrameMs (default 25, with 20 percent of slack) it steps one tier down. There are two lower tiers, "reduced" and "minimal": the render pixel ratio drops to 75 and then 50 percent of the normal one, and the visible edge budget drops to half and then a quarter of maxVisibleEdges. In 2D the visible node budget drops the same way, so a crowded view shows density clusters sooner. In 3D every node stays, because cutting the node list would make nodes vanish instead of thinning out. After idleMs (default 200) without a camera change, full quality returns in one frame.

The tier only goes down while the camera moves and only goes up at rest, so it cannot flicker between tiers. A graph that keeps its frame time never leaves "full", which includes an auto-orbit that runs fast enough. Your data is never changed and no draw call is added. getDiagnostics().interactionQuality reports "full", "reduced" or "minimal".

The budgets scale maxVisibleEdges and maxVisibleNodes, so a graph that is well below them loses nothing but resolution. Slow input also counts: a wheel that ticks less often than targetFrameMs can look like slow frames, so raise targetFrameMs if you see the tier drop on small graphs.

In 3D, depth of field keeps the selected nodes sharp and blurs the rest of the graph with its distance from them, in front and behind, so a selection stands out without dimming anything:

const graph = new Graphraum(container, {
mode: "3d",
depthOfField: { enabled: true, strength: 0.5 },
});
graph.setSelection(["ada"]); // the focus moves to Ada
await graph.setDepthOfField({ strength: 0.8 }); // fades to the new strength; omitted fields keep their values
graph.setDepthOfField({ enabled: false }); // fades out

It is off by default. It behaves like a camera lens. A surface at distance d from the camera, with the focus at distance f, blurs by strength × 24 × |d − f| / d CSS pixels, up to maxBlur (default 12):

  • Surfaces in front of the focus blur faster than those behind it, and a blurred node in front softly covers what is behind it.
  • The closer the camera is to the focus, the shallower the depth of field. Zooming in on a node blurs its surroundings more, and zooming out to an overview sharpens the graph.
  • The blur depends only on ratios of distances, so it looks the same whatever units your layout uses.
  • A flat graph seen head-on is all at one depth, so it only blurs once you rotate it.
OptionDefaultEffect
strength0.5Aperture, 0 to 1.
nearStrengthstrengthAperture for what lies between the camera and the focus, 0 to 1. Set it above strength, with a larger maxBlur, to melt the foreground while the background keeps the softer blur.
maxBlur12Largest blur radius in CSS pixels.
minBlur0Blur radii below this many CSS pixels render sharp, which widens the in-focus band.
nearDistance, farDistance0, InfinityCamera-to-focus distances in world units. strength applies fully up to nearDistance and fades out by farDistance, so an overview from far away can stay sharp.
focus"selection""selection", or a fixed camera distance in world units.
transition{ durationMs: 400, easing: "easeInOut" }How focus moves and blur fades animate.

With focus: "selection" the focal plane goes through the mean position of the selected nodes. graphraum measures its distance from the camera again every frame, so the selected nodes stay sharp while the camera orbits, pans, zooms or flies; only a selection change moves the focus. When nothing is selected the blur fades out and the whole graph is sharp. A number as focus fixes the focal plane at that camera distance instead; it then blurs whether or not anything is selected.

Changing the selection, turning depth of field on or off and changing strength all animate over transition. easing is "linear", "easeIn", "easeOut", "easeInOut" or your own function from progress 0..1 to 0..1:

graph.setDepthOfField({ transition: { durationMs: 800, easing: (t) => 1 - (1 - t) ** 2 } });
const arrived = await graph.setDepthOfField({ enabled: false }); // true once the blur has faded out
graph.setDepthOfField({ strength: 1 }, { animate: false }); // jump

A change during a fade continues from the blur on screen instead of starting over, and the interrupted call resolves false. With prefers-reduced-motion: reduce, durationMs: 0 or { animate: false } it jumps.

Depth of field is a post-process. While it blurs, each frame:

  1. draws the scene into an offscreen target;
  2. draws the edges again to record their depth;
  3. finds how far blurred nodes in front of the focus spread, per screen tile;
  4. blurs at half resolution;
  5. composites onto the canvas.

That adds 4 draw calls. A fade or focus move renders frames until it ends; otherwise it renders on demand like the rest of graphraum. It has no cost while disabled, in 2D, or with nothing selected: frames then render directly and no render targets exist.

Picking, getNodeScreenPosition and DOM overlays such as labels, toolbars and focus cards are unaffected, so labels stay sharp. Glow halos take the depth of what is behind them, so they blur like that.

In 2D there is no depth to focus on, so depth of field does nothing there; setMode("3d") brings it back. If the WebGL context cannot run it, frames render without it and graphraum logs one console warning. getDiagnostics().depthOfField reports "off", "inactive", "active" or "unsupported".

mode: "radial" is a second way to focus, in 2D and 3D. The selected, focused and hovered nodes and their one-hop neighbours stay crisp, with the edges between them. Everything else, edges included, blurs more the farther it is from the selection on screen, smoothly, with no ring. It ignores focus and strength; maxBlur is the largest blur.

graph.setDepthOfField({
enabled: true,
mode: "radial",
innerRadius: 0.15, // viewport heights around the selection that stay crisp
outerRadius: 0.65, // viewport heights at which the blur reaches maxBlur
maxBlur: 12, // CSS pixels
vignette: true, // darken toward the viewport edges, off by default
vignetteStrength: 0.35,
});

The vignette is theme aware: on a dark background it darkens the edges, on a light one it dims them toward the background tone. It fades with the blur. Switching mode live swaps the effect; enabling and disabling fade like depth of field. Each frame adds 3 draw calls plus the crisp nodes and edges, and the crisp set is capped at 1,024 nodes. With density clusters on, nothing is kept crisp.

In 3D, nodes can look like objects in a lit space instead of flat discs. One call sets the look:

import { graphraumScenes } from "@yggy-tech/graphraum";
graph.setScene(graphraumScenes.lit); // spheres lit by a sun, edges pass in front of and behind them
graph.setScene(graphraumScenes.toon); // the same light in three hard bands
graph.setScene(graphraumScenes.flat); // today's flat shapes, edges still share depth
  • lit turns circles into spheres lit by a directional sun and a sky and ground ambient, with a soft highlight. Other shapes get a bevel.
  • toon uses the same light, quantised into three bands with a hard highlight.
  • The node stroke stays unlit, so it reads as a rim around the node. Set strokeWidth: 0 for no border.

The sun is fixed in the world, so the lit side stays put while the camera orbits. Change it, or the ambient light, without touching the rest:

graph.setScene({ sun: { azimuth: 90, elevation: 30 } }); // light from the side
graph.setScene({ ambient: { intensity: 0.8 } }); // softer shadows on the far side

Shading costs no extra draw calls and changing the sun does not recompile shaders. In 2D everything renders flat; getDiagnostics().shading reports what is in effect.

theme.endpointAttach ("boundary" by default) stops each edge at its node’s outline, stroke included, with a small clearance; "center" joins node centers. The same trim is exported for hosts that draw their own edge geometry, such as overlays or exported paths:

import { attachPointOnOutline, trimEdgeEndpoints } from "@yggy-tech/graphraum";
const { source, target } = trimEdgeEndpoints({
source: { x: 0, y: 0, z: 0 },
target: { x: 30, y: 0, z: 40 },
sourceOutline: { size: 4 },
targetOutline: { shape: "pill", width: 12, height: 3 },
clearance: 0.75, // world units, the default
mode: "3d", // "2d" by default
});
const end = attachPointOnOutline(center, farPoint, { size: 4 }, 0.75, "3d");

Pass the renderer’s mode. "2d" measures the outline in the xy plane and ignores z. "3d" stops one outline radius from each center along the 3D segment, because node billboards face the camera. The radius is taken along the edge’s xy heading, so circles meet their outline from every view; other shapes are approximate in 3D and can end slightly inside or short of the outline, depending on the camera.