WebGPU Network Graph Visualization Library – GraphGPU

Category: Chart & Graph , Javascript | November 30, 2026
Authordrkameleon
Last UpdateNovember 30, 2026
LicenseMIT
Tags
Views0 views
WebGPU Network Graph Visualization Library – GraphGPU

GraphGPU is a JavaScript library for rendering interactive network graphs with WebGPU.

It offers CPU and GPU force-directed layouts for knowledge graphs, service dependency maps, and other connected data.

Features

  • Rendering on demand as the graph or camera changes.
  • CPU force simulation with Barnes-Hut approximation and optional Web Worker execution.
  • Continuous physics, node pinning, and circular and grid layouts.
  • Zooming, panning, node dragging, and multiple selection.
  • Built-in color palettes with automatic coloring by node and edge tag.
  • Graph editing, node lookup, and camera controls.

How to use it

Installation

Install and import GraphGPU with NPM:

npm install graphgpu
import { GraphGPU } from 'graphgpu';

For a plain HTML page, import the CDN module as shown in the next example. You can also download graphgpu.standalone.min.js and load it in your document.

Basic usage

Create a canvas with a defined height. This example represents services and databases as nodes. The tags identify entity types and relationships.

<canvas id="network" style="display:block;width:100%;height:480px"></canvas>
<script type="module">
  import { GraphGPU } from 'https://cdn.jsdelivr.net/npm/graphgpu/+esm';
  const graph = new GraphGPU({
    canvas: '#network',
    nodeSize: 8,
    edgeOpacity: 0.6,
    palette: 'vibrant'
  });
  if (!(await graph.init())) {
    throw new Error('Graph rendering is unavailable');
  }
  const app = graph.put('Service', { name: 'Web App' });
  const api = graph.put('Service', { name: 'API' });
  const db = graph.put('Database', { name: 'PostgreSQL' });
  const cache = graph.put('Database', { name: 'Redis' });
  graph.link(app, 'requests', api);
  graph.link(api, 'reads', db);
  graph.link(api, 'caches', cache);
  graph.on('layout:stop', () => graph.fitView());
  graph.startLayout();
</script>

To use the standalone file, add the following tag before the module script. Replace its import statement with const { GraphGPU } = window.GraphGPU.

<script src="graphgpu.standalone.min.js"></script>

Build from source for WebGL2 and additional layouts

Use the source build for WebGL2 fallback, hierarchical, tree, radial, and concentric layouts, arrows, parallel edges, self-loops, data-driven styles, keyboard navigation, and image export.

Run these commands with Node.js :

git clone https://github.com/drkameleon/GraphGPU.git
cd GraphGPU
git checkout 72ab976b9a1b87d9a3207a458cbf6c30ddab1acd
npm ci
npm run build
npx esbuild src/index.ts --bundle --format=iife --global-name=GraphGPU --target=es2022 --minify --outfile=dist/graphgpu.standalone.min.js

Copy dist/graphgpu.standalone.min.js to your HTML directory and use the standalone setup above. For a bundled project next to the cloned GraphGPU directory, run npm install ../GraphGPU from the project directory and import the GraphGPU class from the package.

Visualize dependencies with a directed layout

Use a hierarchical layout when the order of dependencies matters. Add the following code to the module script after graph.startLayout().

graph.setArrows(true);
graph.setEdgeLabelsVisible(true);
graph.setLabelOptions({ position: 'below' });
await graph.applyLayout('hierarchical', {
  direction: 'LR',
  animate: true
});
await graph.fitView(0.15);

Style the graph from
application data

Assign shapes and colors to service and database nodes, and use different line styles for different relationships.

graph.setStyle({
  nodes: {
    '*': { caption: 'name' },
    Service: { color: '#16a34a', shape: 'square' },
    Database: { color: '#ea580c', shape: 'hexagon' }
  },
  edges: {
    requests: { width: 2, opacity: 0.85 },
    caches: { dash: 'dashed' }
  }
});

Expand the graph from application records

Assign unique external keys to application records. Use upsert() to reuse a keyed node when you load the same record again.

const queue = graph.upsert('service:queue', 'Service', {
  name: 'Message Queue'
});
const service = graph.fetch('Service', { name: 'API' })[0];
graph.link(service.id, 'publishes', queue);
await graph.applyLayout('hierarchical', { direction: 'LR' });
graph.highlightNeighbors(service.id);
await graph.focusNode(service.id, 3, { animate: true });

Configuration options

Pass these options to new GraphGPU(options).

General options

Color values accept CSS color strings (hex, RGB, HSL, or named colors), normalized RGB/RGBA arrays, and { r, g, b, a? } objects in fields that accept a color.

OptionDescription
canvasRequired. A canvas selector or HTMLCanvasElement.
nodeSizeNumber. Node radius scale, default 6 (world radius =
node size × scale × 0.01).
minNodeSizeNumber. Minimum on-screen radius in CSS pixels, default
1.5; 0 disables the limit.
maxNodeSizeNumber. Maximum on-screen radius in CSS pixels, default
0 (unlimited).
maxNodesNumber. Initial node capacity, default 4096; grows as
needed.
maxEdgesNumber. Initial edge capacity, default 8192; grows as
needed.
edgeOpacityNumber from 0 to 1, default 0.12.
edgeWidthNumber. Fixed line width in CSS pixels, default 0
(scales with nodes).
arrowsBoolean. Draw arrowheads at targets, default
false.
palettePalette name or { name, colors }; default 'default'. Built-in names: default, vibrant, pastel, earthy, inferno, playful, viridis, rainbow.
backgroundColor, default [0.02, 0.02, 0.04, 1]. Alpha below 1 (or 'transparent') reveals the page background.
antialiasBoolean. Enable antialiasing, default true.
pixelRatioNumber. Rendering pixel ratio, default devicePixelRatio; follows
changes when not overridden.
autoResizeBoolean. Track canvas size via ResizeObserver, default
true.
seedNumber. Repeatable initial positions, default 1;
external keys determine keyed positions.
iconFontCSS font-family for node icons; defaults to system emoji fonts and
sans-serif.
renderer'auto' (default), 'webgpu', or
'webgl'. Auto selects WebGPU and falls back to WebGL2.
cullingWebGPU only. true, false, or
'auto' (default; activates at 20,000 combined nodes and
edges).
edgeDensityWebGPU only. true, false (default), or
'auto' (activates at 100,000 edges). Accumulates
overlapping edges into a tone-mapped density view.
layoutDefault layout settings; see Layout options.
interactionPointer, selection, and keyboard settings; see Interaction
options.
labelsNode and edge text settings; see Label options.
onWebGPUUnavailableCallback when automatic initialization finds neither backend, or a
forced WebGPU backend is unavailable.
onDeviceLostCallback receiving { reason, message } on device loss;
the library attempts recovery.
onErrorCallback receiving a GraphGPUError object; see Events.

Layout options

Pass these settings through layout in the constructor or to startLayout() where applicable.

OptionDescription
type'none' (default), 'force',
'force-gpu', 'circular', 'grid',
'hierarchical', 'tree', 'radial',
or 'concentric'. A configured layout starts once nodes
exist after initialization.
engine'auto' (default), 'cpu', or 'gpu'. Auto uses GPU at 5,000+ nodes with WebGPU, and CPU with WebGL2 or explicit CPU-only settings.
gravitationalConstantRepulsion strength, default -0.25. Negative values
repel.
barnesHutThetaCPU approximation parameter, default 0.3;
0 computes exact pairwise repulsion.
springLengthRest length of edge springs, default 0.2.
springConstantEdge spring stiffness, default 0.06.
edgeWeightInfluenceWeight exponent for spring strength, default 1; 0 ignores weights. The stiffness multiplier is capped at 50. Nonpositive weights produce no spring when weights are used.
degreeMassBoolean, default true. Adjust node mass based on degree
relative to the median.
preventOverlapBoolean, default true. Repel overlapping nodes based on
their radii.
radiusScaleNumber. Layout radius per unit node size; derives from
nodeSize (0.06 at the default scale).
centralGravityStrength of attraction toward the center, default
0.012.
dampingVelocity friction, default 0.18.
timestepIntegration step, default 0.35.
maxVelocityVelocity clamp, default 0.06.
minVelocityStabilization velocity threshold, default 0.0005.
maxIterationsMaximum simulation ticks before stopping, default
1000.
useWorkerCPU layout: true, false, or 'auto' (default; worker at 2,000+ nodes). Uses the main thread if workers are unavailable.
frameBudgetCPU frame budget in milliseconds, default 8; up to
three ticks per frame, at least one.
repulsionLegacy repulsion magnitude; maps to a negative
gravitationalConstant.
attractionLegacy alias for springConstant.
gravityLegacy alias for centralGravity.

The GPU-specific startGPULayout() accepts the shared physics parameters (excluding CPU-only settings), plus:

OptionDescription
stepsPerFrameGPU simulation steps per frame, default 3.
approximateRepulsionfalse for exact repulsion, true or
'tree' for Barnes-Hut, 'grid' for uniform-grid
approximation, or 'auto' (default; tree above 16,384
nodes).

The static layouts accept the following options through applyLayout(type, options):

OptionDescription
spacingDistance between nodes in world units; calculated from node size by
default.
centerCenter coordinates, default [0, 0].
directionHierarchical and tree direction: 'TB' (default),
'BT', 'LR', or 'RL'.
levelSpacingLayer, tree-level, or ring spacing; defaults to 2.5 times
spacing.
rootsArray of node IDs or keys for tree or radial layout; a root is
chosen per connected component by default.
valueFunction receiving a node; controls placement in concentric rings,
highest values at the center. Defaults to node degree.
animateBoolean or duration in milliseconds. Omitted or false jumps to the
layout; true animates for 500 ms.

Interaction options

Set these properties inside interaction:

OptionDescription
panAllow panning, default true.
zoomAllow scroll and pinch zoom, default true.
zoomRangeMinimum and maximum zoom, default [0.01, 100].
dragNodesEnable node dragging, default true. Drag a selected node to move the selection as a group. Explicitly pinned nodes stay pinned after dragging.
hoverEnable hover detection, default true.
selectionEnable node and edge selection, default true.
multiSelectEnable modifier-key selection, default true. Hold Shift, Ctrl, or Command while clicking to add to the selection.
lassoEnable rectangular selection by Shift-drag on empty space, default
false.
hoverRingDraw a ring around the hovered node, default true.
highlightNeighborsEmphasize the hovered or selected node and its neighbors, default
false.
keyboardEnable keyboard navigation, default true.
ariaLabelCanvas accessible name, default 'Graph'.
gpuPickingWebGPU picking: true, false, or
'auto' (default; uses GPU picking during GPU layout).

Label options

Set these properties inside labels or update them with setLabelOptions().

OptionDescription
enabledBoolean. Show labels, default true.
fontCSS font family; defaults to -apple-system,"Segoe UI",Helvetica,Arial,sans-serif.
colorColor for node text, auto-contrast by default.
visibleAtZoomMinimum zoom level for labels. Omit to apply no zoom threshold.
propertyNode property to display; defaults to name, title, or tag.
maxLengthMaximum character count before adding an ellipsis. Omit or set to 0 for no truncation.
position'inside' (default) or 'below'.
formatFunction (node) => string. Return undefined or an empty string to hide the label. Overrides property and style captions.
minNodeRadiusMinimum on-screen radius for a label: 16 CSS pixels inside, 4
below.
haloBoolean or color. Text outline, enabled by default below nodes.
gpuBoolean, default false. WebGPU text rendering;
below-node labels and WebGL2 use Canvas2D. Use Canvas2D for scripts
requiring text shaping.
edgesBoolean (default true) or { property?, color? }. The
edge tag is the default text.

API methods

Initialization and graph data

External keys are unique strings. Methods that accept node or edge references accept their corresponding numeric IDs or keys.

Method or propertyDescription
init()Asynchronously initialize rendering. Await the boolean result before
using the graph.
put(tag, properties?, opts?)Add a tagged node and return its numeric ID. Also accepts put(tag, label, properties?, opts?), where the label sets the name. After the first layout, new nodes with no coordinates start near their linked neighbors.
putMany(tag, items)Batch-add nodes from property objects; returns node IDs.
link(source, tag, target, properties?, opts?)Add edges and return an array of edge IDs. Endpoints can be IDs, keys, or arrays. Batch linking connects every source to every target; an invalid endpoint throws a RangeError.
unput(id)Remove a node and its incident edges. Removed IDs are never reused.
unlink(edgeId)Remove an edge. Removed edge IDs are never reused.
clear()Remove all nodes and edges.
fetch(tag, filter?)Return nodes with the tag and optional matching properties.
what(id)Return a node or null.
edge(id)Return an edge or null.
update(id, changes)Apply node changes; returns whether the node exists.
updateEdge(id, changes)Apply edge changes; returns whether the edge exists.
upsert(key, tag, properties?, opts?)Create or update a keyed node; returns its ID.
related(id)Return neighboring nodes.
edges(nodeId)Return edges connected to a node.
tags()Return node tags.
nodeCount / edgeCountRead the number of nodes or edges.
setVisible(ids, visible) /
setEdgesVisible(ids, visible)
Show or hide nodes or edges by ID/key. Hiding a node also hides incident edges. Hidden items retain data and selection; layouts can still move them.
filter(nodePredicate?, edgePredicate?)Display items accepted by the supplied predicates; omitting a
predicate shows all items of that kind.
showAll()Clear visibility filters.
isVisible(id) / isEdgeVisible(id)Check node or edge visibility.

Node and edge parameters

Node records returned by what() and fetch() expose id, key (if assigned), tag, properties, x, y, size, color channels r, g, b, a, and any assigned shape, border, icon, or image. Edge records expose id, key (if assigned), tag, source, target, weight, properties, and any assigned width, opacity, or dash pattern.

Load icon fonts before using their glyphs. Remote node images require suitable CORS headers. The shared texture atlas holds up to 512 distinct images and icons.

ParameterDescription
put() optionsx, y (world coordinates);
size; color (string); key;
near (neighbor ID or key); plus the node appearance fields
below.
Node appearanceshape (circle by default, square, diamond, triangle, hexagon), borderWidth (CSS px; thin dark rim by default, 0 removes the border), borderColor, icon (character, emoji, font glyph), image (URL or CanvasImageSource).
update() changestag, properties,
replaceProperties (true to replace all properties;
otherwise merges), color, size,
x, y, and all node appearance fields. Null
color or appearance overrides reset to rules/defaults.
link() optionskey (single edge only), weight (spring weight, default 1), width (CSS px), opacity (0 to 1), dash ('solid', 'dashed', 'dotted', 'dash-dot').
updateEdge() changestag, properties,
replaceProperties, color, weight,
width, opacity, dash. Null color,
width, opacity, or dash resets the override.

Layout and viewport

Camera movement methods return promises and accept { animate: true } for a 400 ms transition or { animate: ms } for a custom duration. User panning, zooming, or another camera move interrupts a transition. Camera and layout transitions respect the reduced-motion preference.

MethodDescription
startLayout(opts?)Start a force simulation on the CPU or GPU; replaces the running
layout.
stopLayout()Stop the running simulation or cancel stabilization.
stabilize(opts?)Run CPU physics until it stabilizes or reaches iterations. Yields between batches and returns a promise for the tick count. The onProgress(iteration, energy) callback reports progress.
stepLayout(n?)Run n CPU simulation ticks synchronously, default 1; returns the
number executed.
startGPULayout(opts?)Asynchronously start GPU compute layout; falls back to CPU when
unavailable.
stopGPULayout()Stop and dispose of GPU layout resources.
applyLayout(type, opts?)Stop the running layout and apply a circular, grid, hierarchical,
tree, radial, or concentric layout. Resolves when the move finishes or
is interrupted.
setAnimated(bool)Toggle continuous CPU physics. With animation enabled, the simulation continues even after stabilization.
pinNode(id) / unpinNode(id)Keep a node fixed across force layouts or return it to the simulation.
isPinned(id) / getPinnedNodes()Check pin status or retrieve pinned node IDs.
resetPositions()Reset node positions using the configured seed.
fitView(padding?, nodes?, opts?)Fit all visible nodes or specified nodes. Default padding is
0.1.
focusNode(id, zoom?, opts?)Center on a node and optionally set zoom.
setView(x, y, zoom?, opts?)Set camera center and optional zoom.
getView()Return camera state (x, y, zoom, rotation).
resetView(opts?)Restore the default camera.
worldToScreen(x, y) /
screenToWorld(x, y)
Convert coordinates between world units and CSS pixels from the
canvas’s top-left corner. Returns a coordinate pair.
getNodeScreenPosition(id)Return a node’s CSS-pixel coordinates or null.
pickAt(x, y)Asynchronously return { node }, { edge },
or null at a CSS-pixel point.
resize()Recalculate canvas size; useful with automatic resizing
disabled.

Appearance and export

Method or propertyDescription
setPalette(nameOrPalette)Switch tag colors, preserving explicit overrides.
GraphGPU.palettesBuilt-in palette definitions (standalone:
GraphGPU.GraphGPU.palettes).
setBackground(color)Update the canvas background.
setNodeSize(size)Change the node radius scale.
setNodeSizeLimits(min, max?)Set on-screen node radius limits in CSS px; 0 disables a limit. The optional maximum defaults to 0.
setEdgeOpacity(opacity)Update edge opacity.
setEdgeWidth(px)Change the fixed width; 0 scales width with node size.
setArrows(bool)Toggle directional arrowheads.
setEdgeDensity(mode)Switch WebGPU edge density (true, false,
'auto').
setLabelsVisible(bool)Show or hide all labels.
setEdgeLabelsVisible(bool)Show or hide edge labels independently of node labels.
setLabelOptions(opts)Merge new label settings.
getTagColors()Return a Map of tag colors as { bg: [r,g,b,a] }.
setStyle(rules)Replace node and edge style rules and recalculate mapping domains. See Style rules.
getStyle()Return the active style rules.
getBackend()Return 'webgpu', 'webgl', or null before initialization or if neither works.
getFps()Return frames drawn per second; 0 when idle.
toImage(opts?)Return a promise for an image Blob of the current view.

Style rules

Pass nodes and edges objects to setStyle(). A tag-specific rule takes precedence over '*'; direct node and edge overrides take precedence over both.

Numeric and continuous color mappings default to the minimum and maximum property values when the style is set.

RuleDescription
Node fieldscolor, size, shape, icon, image, borderWidth, borderColor, caption.
Edge fieldscolor, width, opacity, dash, caption.
Numeric mapping{ property, range?, domain? } for size, borderWidth, width, or opacity. Uses the property value when range is omitted.
Color mapping{ property, map?, range?, domain? } for color or borderColor. Use map to assign colors by value or range for a numeric gradient. Omitting both assigns palette colors by value.
Icon and image mappingA constant icon or image, or { property } to read it from the node.
CaptionA property name or a function receiving the node or edge.

Image export options

OptionDescription
scaleResolution multiplier, default 1; capped by graphics
backend limits.
typeMIME type, default 'image/png'.
qualityNumber from 0 to 1 for lossy formats such as JPEG or WebP.
labelsInclude labels, default true.
backgroundOptional color behind the graph.

Selection and highlighting

MethodDescription
setSelectionEnabled(bool)Enable or disable selection.
setMultiSelectEnabled(bool)Toggle always-on multiple selection.
selectNodes(ids, additive?) /
selectEdges(ids, additive?)
Replace selection or add to it when additive is true. Accept
IDs/keys or arrays; emit selection events.
deselect(nodes?, edges?)Deselect the nodes or edges in the supplied ID/key arrays.
clearSelection()Deselect everything.
getSelectedNodes() /
getSelectedEdges()
Return selected numeric IDs.
highlight(nodes, edges?)Emphasize specified nodes and edges; defaults to edges between the
nodes.
highlightNeighbors(nodes)Highlight nodes, their neighbors, and their connections.
clearHighlight()Remove highlight effects.
setKeyboardFocus(id)Focus a node by ID/key, or clear focus with null.
getKeyboardFocus()Return the focused node ID or null.

Rendering and cleanup

Method or propertyDescription
positions / colorsRaw Float32Array position and color buffers.
markDirty()Flag direct buffer updates for upload.
requestRender()Trigger a redraw after an external change.
getGraph()Access the underlying Graph object. Its methods use buffer slots;
convert with nodeSlot(id), nodeHandle(slot),
edgeSlot(id), or edgeHandle(slot).
pause() / resume()Pause or resume rendering.
destroy()Release graphics resources, layout resources, and event listeners
when removing the graph.

Events

Register a handler with on(event, handler) and use off(event, handler) with the same function when you no longer need the listener.

function handleNodeClick(event) {
  console.log(event.target.properties);
}
graph.on('node:click', handleNodeClick);

Every event has a type and target. Node and edge pointer events return the corresponding record; empty-canvas clicks return null. Pointer-driven events also expose x, y (CSS pixels relative to the canvas), worldX, worldY, and originalEvent.

Context menu gestures include a stationary 500 ms touch press. Register a context menu handler to suppress the native menu for that event.

EventFires when
node:click / node:dblclickA node is clicked or double-clicked.
node:contextmenuA node receives a context menu gesture.
node:focusKeyboard focus changes. The target is the focused node or null.
node:hover / node:hoveroutPointer enters or leaves a node.
node:dragstart / node:drag /
node:dragend
Node dragging starts, continues, or ends.
node:select / node:deselectNode selection changes.
edge:click / edge:dblclickAn edge is clicked or double-clicked.
edge:contextmenuAn edge receives a context menu gesture.
edge:hover / edge:hoveroutPointer enters or leaves an edge.
edge:select / edge:deselectEdge selection changes.
canvas:click / canvas:dblclickEmpty canvas is clicked or double-clicked.
canvas:contextmenuEmpty canvas receives a context menu gesture.
canvas:pan / canvas:zoomCamera is panned or zoomed. The target contains x, y, zoom, and rotation.
layout:start / layout:stopLayout simulation starts or stops. The start event target contains { gpu: boolean }; the stop event target is null.
layout:tickSimulation tick; target contains iteration and energy.
render:frameA frame renders; target includes fps, frameTime (CPU ms), nodeCount,
edgeCount, visibleNodes, visibleEdges, and gpuTime when timestamp
queries are available.
errorA graphics error; target contains kind and message. Kinds:
validation, out-of-memory, internal, device-lost, limit.

Keyboard controls

KeyAction
Arrow keysPan, or move focus to the nearest node in that direction when a node
has focus. Shift + arrow pans.
Tab / Shift + TabMove to the next or previous node; leave the canvas at either
end.
Enter / SpaceSelect the focused node. Shift/Ctrl/Command adds it to the
selection.
EscapeClear node focus first, or clear selection.
+ / – / 0Zoom in, zoom out, or fit the graph.
Ctrl/Command + ASelect all.

Alternatives

You Might Be Interested In:


Leave a Reply