
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.
| Option | Description |
|---|---|
canvas | Required. A canvas selector or HTMLCanvasElement. |
nodeSize | Number. Node radius scale, default 6 (world radius =node size × scale × 0.01). |
minNodeSize | Number. Minimum on-screen radius in CSS pixels, default1.5; 0 disables the limit. |
maxNodeSize | Number. Maximum on-screen radius in CSS pixels, default0 (unlimited). |
maxNodes | Number. Initial node capacity, default 4096; grows asneeded. |
maxEdges | Number. Initial edge capacity, default 8192; grows asneeded. |
edgeOpacity | Number from 0 to 1, default 0.12. |
edgeWidth | Number. Fixed line width in CSS pixels, default 0(scales with nodes). |
arrows | Boolean. Draw arrowheads at targets, defaultfalse. |
palette | Palette name or { name, colors }; default 'default'. Built-in names: default, vibrant, pastel, earthy, inferno, playful, viridis, rainbow. |
background | Color, default [0.02, 0.02, 0.04, 1]. Alpha below 1 (or 'transparent') reveals the page background. |
antialias | Boolean. Enable antialiasing, default true. |
pixelRatio | Number. Rendering pixel ratio, default devicePixelRatio; follows changes when not overridden. |
autoResize | Boolean. Track canvas size via ResizeObserver, defaulttrue. |
seed | Number. Repeatable initial positions, default 1;external keys determine keyed positions. |
iconFont | CSS 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. |
culling | WebGPU only. true, false, or'auto' (default; activates at 20,000 combined nodes andedges). |
edgeDensity | WebGPU only. true, false (default), or'auto' (activates at 100,000 edges). Accumulatesoverlapping edges into a tone-mapped density view. |
layout | Default layout settings; see Layout options. |
interaction | Pointer, selection, and keyboard settings; see Interaction options. |
labels | Node and edge text settings; see Label options. |
onWebGPUUnavailable | Callback when automatic initialization finds neither backend, or a forced WebGPU backend is unavailable. |
onDeviceLost | Callback receiving { reason, message } on device loss;the library attempts recovery. |
onError | Callback receiving a GraphGPUError object; see Events. |
Layout options
Pass these settings through layout in the constructor or to startLayout() where applicable.
| Option | Description |
|---|---|
type | 'none' (default), 'force','force-gpu', 'circular', 'grid','hierarchical', 'tree', 'radial',or 'concentric'. A configured layout starts once nodesexist 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. |
gravitationalConstant | Repulsion strength, default -0.25. Negative valuesrepel. |
barnesHutTheta | CPU approximation parameter, default 0.3;0 computes exact pairwise repulsion. |
springLength | Rest length of edge springs, default 0.2. |
springConstant | Edge spring stiffness, default 0.06. |
edgeWeightInfluence | Weight 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. |
degreeMass | Boolean, default true. Adjust node mass based on degreerelative to the median. |
preventOverlap | Boolean, default true. Repel overlapping nodes based ontheir radii. |
radiusScale | Number. Layout radius per unit node size; derives fromnodeSize (0.06 at the default scale). |
centralGravity | Strength of attraction toward the center, default0.012. |
damping | Velocity friction, default 0.18. |
timestep | Integration step, default 0.35. |
maxVelocity | Velocity clamp, default 0.06. |
minVelocity | Stabilization velocity threshold, default 0.0005. |
maxIterations | Maximum simulation ticks before stopping, default1000. |
useWorker | CPU layout: true, false, or 'auto' (default; worker at 2,000+ nodes). Uses the main thread if workers are unavailable. |
frameBudget | CPU frame budget in milliseconds, default 8; up tothree ticks per frame, at least one. |
repulsion | Legacy repulsion magnitude; maps to a negative gravitationalConstant. |
attraction | Legacy alias for springConstant. |
gravity | Legacy alias for centralGravity. |
The GPU-specific startGPULayout() accepts the shared physics parameters (excluding CPU-only settings), plus:
| Option | Description |
|---|---|
stepsPerFrame | GPU simulation steps per frame, default 3. |
approximateRepulsion | false for exact repulsion, true or'tree' for Barnes-Hut, 'grid' for uniform-gridapproximation, or 'auto' (default; tree above 16,384nodes). |
The static layouts accept the following options through applyLayout(type, options):
| Option | Description |
|---|---|
spacing | Distance between nodes in world units; calculated from node size by default. |
center | Center coordinates, default [0, 0]. |
direction | Hierarchical and tree direction: 'TB' (default),'BT', 'LR', or 'RL'. |
levelSpacing | Layer, tree-level, or ring spacing; defaults to 2.5 times spacing. |
roots | Array of node IDs or keys for tree or radial layout; a root is chosen per connected component by default. |
value | Function receiving a node; controls placement in concentric rings, highest values at the center. Defaults to node degree. |
animate | Boolean or duration in milliseconds. Omitted or false jumps to the layout; true animates for 500 ms. |
Interaction options
Set these properties inside interaction:
| Option | Description |
|---|---|
pan | Allow panning, default true. |
zoom | Allow scroll and pinch zoom, default true. |
zoomRange | Minimum and maximum zoom, default [0.01, 100]. |
dragNodes | Enable node dragging, default true. Drag a selected node to move the selection as a group. Explicitly pinned nodes stay pinned after dragging. |
hover | Enable hover detection, default true. |
selection | Enable node and edge selection, default true. |
multiSelect | Enable modifier-key selection, default true. Hold Shift, Ctrl, or Command while clicking to add to the selection. |
lasso | Enable rectangular selection by Shift-drag on empty space, defaultfalse. |
hoverRing | Draw a ring around the hovered node, default true. |
highlightNeighbors | Emphasize the hovered or selected node and its neighbors, defaultfalse. |
keyboard | Enable keyboard navigation, default true. |
ariaLabel | Canvas accessible name, default 'Graph'. |
gpuPicking | WebGPU picking: true, false, or'auto' (default; uses GPU picking during GPU layout). |
Label options
Set these properties inside labels or update them with setLabelOptions().
| Option | Description |
|---|---|
enabled | Boolean. Show labels, default true. |
font | CSS font family; defaults to -apple-system,"Segoe UI",Helvetica,Arial,sans-serif. |
color | Color for node text, auto-contrast by default. |
visibleAtZoom | Minimum zoom level for labels. Omit to apply no zoom threshold. |
property | Node property to display; defaults to name, title, or tag. |
maxLength | Maximum character count before adding an ellipsis. Omit or set to 0 for no truncation. |
position | 'inside' (default) or 'below'. |
format | Function (node) => string. Return undefined or an empty string to hide the label. Overrides property and style captions. |
minNodeRadius | Minimum on-screen radius for a label: 16 CSS pixels inside, 4 below. |
halo | Boolean or color. Text outline, enabled by default below nodes. |
gpu | Boolean, default false. WebGPU text rendering;below-node labels and WebGL2 use Canvas2D. Use Canvas2D for scripts requiring text shaping. |
edges | Boolean (default true) or { property?, color? }. Theedge 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 property | Description |
|---|---|
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 / edgeCount | Read 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.
| Parameter | Description |
|---|---|
put() options | x, y (world coordinates);size; color (string); key;near (neighbor ID or key); plus the node appearance fieldsbelow. |
| Node appearance | shape (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() changes | tag, properties,replaceProperties (true to replace all properties;otherwise merges), color, size,x, y, and all node appearance fields. Nullcolor or appearance overrides reset to rules/defaults. |
link() options | key (single edge only), weight (spring weight, default 1), width (CSS px), opacity (0 to 1), dash ('solid', 'dashed', 'dotted', 'dash-dot'). |
updateEdge() changes | tag, 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.
| Method | Description |
|---|---|
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 property | Description |
|---|---|
setPalette(nameOrPalette) | Switch tag colors, preserving explicit overrides. |
GraphGPU.palettes | Built-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.
| Rule | Description |
|---|---|
| Node fields | color, size, shape, icon, image, borderWidth, borderColor, caption. |
| Edge fields | color, 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 mapping | A constant icon or image, or { property } to read it from the node. |
| Caption | A property name or a function receiving the node or edge. |
Image export options
| Option | Description |
|---|---|
scale | Resolution multiplier, default 1; capped by graphicsbackend limits. |
type | MIME type, default 'image/png'. |
quality | Number from 0 to 1 for lossy formats such as JPEG or WebP. |
labels | Include labels, default true. |
background | Optional color behind the graph. |
Selection and highlighting
| Method | Description |
|---|---|
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 property | Description |
|---|---|
positions / colors | Raw 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.
| Event | Fires when |
|---|---|
node:click / node:dblclick | A node is clicked or double-clicked. |
node:contextmenu | A node receives a context menu gesture. |
node:focus | Keyboard focus changes. The target is the focused node or null. |
node:hover / node:hoverout | Pointer enters or leaves a node. |
node:dragstart / node:drag /node:dragend | Node dragging starts, continues, or ends. |
node:select / node:deselect | Node selection changes. |
edge:click / edge:dblclick | An edge is clicked or double-clicked. |
edge:contextmenu | An edge receives a context menu gesture. |
edge:hover / edge:hoverout | Pointer enters or leaves an edge. |
edge:select / edge:deselect | Edge selection changes. |
canvas:click / canvas:dblclick | Empty canvas is clicked or double-clicked. |
canvas:contextmenu | Empty canvas receives a context menu gesture. |
canvas:pan / canvas:zoom | Camera is panned or zoomed. The target contains x, y, zoom, and rotation. |
layout:start / layout:stop | Layout simulation starts or stops. The start event target contains { gpu: boolean }; the stop event target is null. |
layout:tick | Simulation tick; target contains iteration and energy. |
render:frame | A frame renders; target includes fps, frameTime (CPU ms), nodeCount, edgeCount, visibleNodes, visibleEdges, and gpuTime when timestamp queries are available. |
error | A graphics error; target contains kind and message. Kinds: validation, out-of-memory, internal, device-lost, limit. |
Keyboard controls
| Key | Action |
|---|---|
| Arrow keys | Pan, or move focus to the nearest node in that direction when a node has focus. Shift + arrow pans. |
| Tab / Shift + Tab | Move to the next or previous node; leave the canvas at either end. |
| Enter / Space | Select the focused node. Shift/Ctrl/Command adds it to the selection. |
| Escape | Clear node focus first, or clear selection. |
| + / – / 0 | Zoom in, zoom out, or fit the graph. |
| Ctrl/Command + A | Select all. |
Alternatives
- Customizable Network Graph JavaScript Library – Orb.js
- Create Network Diagrams With Gnet.js JavaScript Library
- Interactive Graph Visualization Using D3.js – ggraph







