Skip to content
D
Documentation

Navigate accessible canvases

how-to
8 min readUpdated

Add a minimap and viewport controls when a diagram extends beyond its visible canvas. Keep navigation on the mounted canvas's camera, provide keyboard and touch access, and inspect the detail the renderer actually draws rather than treating node count as a performance measurement.

Start in the project from your JavaScript, React, Vue, Angular, or Qwik quick start. The files below add a navigation example to that project; keep its entry point, stylesheet imports, framework configuration and mounting wrappers. Render the new component in place of the quick start's flow component. In JavaScript, replace the entry's diagram setup as shown, retaining its stylesheet import.

The quick starts already install the packages these samples use. The commands below install each binding and its peers in another project.

JavaScript:

bash
npm install @grafloria/element @grafloria/renderer @grafloria/engine

React:

bash
npm install @grafloria/react @grafloria/element @grafloria/renderer @grafloria/engine

Vue:

bash
npm install @grafloria/vue @grafloria/element @grafloria/renderer @grafloria/engine

Angular:

bash
npm install @grafloria/angular @grafloria/element @grafloria/renderer @grafloria/engine

Qwik:

bash
npm install -D @grafloria/qwik @grafloria/element @grafloria/renderer @grafloria/engine

1. Add a minimap and controls

The result is a grid of connected nodes, a background grid, a bottom-right overview and the shipped zoom/fit controls. The minimap draws the whole diagram and overlays the visible camera rectangle. Node movement changes its node layer; camera movement changes its camera rectangle.

Use the component's plugins prop first. In JavaScript, render returns a mounted DiagramInstance; pass it to attachCanvasPlugins. Both approaches use the same plugins.

Create the following shared data module at src/navigation-data.ts in each project. NodeSpec and EdgeSpec describe the input data. CanvasPluginOptions configures the plugins. This example changes the background to lines and gives the minimap a compact size and an accessible name.

ts
import type { CanvasPluginOptions, EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = Array.from({ length: 24 }, (_, i) => ({
  id: `n${i}`,
  label: `Step ${i + 1}`,
  position: { x: 40 + (i % 6) * 190, y: 40 + Math.floor(i / 6) * 120 },
  size: { width: 140, height: 64 },
}));

export const edges: EdgeSpec[] = Array.from({ length: 23 }, (_, i) => ({
  id: `e${i}`,
  source: `n${i}`,
  target: `n${i + 1}`,
}));

export const plugins: CanvasPluginOptions = {
  background: { variant: 'lines', gap: 24, color: '#cbd5e1', size: 0.5 },
  minimap: {
    width: 170,
    height: 110,
    ariaLabel: 'Workflow overview',
    nodeColor: '#64748b',
    maskColor: 'rgba(37,99,235,0.12)',
    maskStroke: '#2563eb',
  },
  controls: true,
};

The next step supplies addNavigationTools, used by each binding below. Create that shared module too before running the example. React, Vue and Qwik render their own GrafloriaFlow binding; Angular imports DiagramCanvasComponent. Each ready callback receives the live model and engine, not another diagram.

ts
// src/main.ts
import './style.css';
import { render } from '@grafloria/element';
import { attachCanvasPlugins } from '@grafloria/renderer';
import { nodes, edges, plugins } from './navigation-data';
import { addNavigationTools } from './navigation-tools';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const host = document.createElement('div');
host.style.cssText = 'position:relative;width:100%;height:500px;touch-action:none';
const close = document.createElement('button');
close.textContent = 'Close diagram';
app.replaceChildren(close, host);

const diagram = render({ nodes, edges }, host, {
  zoom: 1.2,
  maxZoom: 4,
  interaction: { enableKeyboardNudge: true },
});
const attachment = attachCanvasPlugins(diagram, plugins);
const stopTools = addNavigationTools(diagram, () => diagram.getQualityState());
close.addEventListener('click', () => {
  stopTools();
  attachment.dispose();
  diagram.dispose();
  host.remove();
  close.remove();
}, { once: true });

The React example shows the connected steps over the line grid, with navigation buttons above the canvas and the overview at bottom-right.

The Vue example renders the same scene and controls through its own binding.

For Qwik, place the two shared modules in src/navigation-data.ts and src/navigation-tools.ts. The ready callback stores the live diagram with noSerialize(). A browser-only visible task tracks that instance, installs the tools and registers their cleanup.

Here, your component cleans up the additional navigation tools; see Group and collapse for binding initialization and diagram disposal.

Compare the result with the live Minimap & controls demo.

2. Navigate through the live camera

Use the instance's ViewportController, or Angular's viewportController(). getViewBox() returns the visible world rectangle; getViewport() returns the camera rectangle whose width and height are CSS pixels. getZoom() returns the current scale. clientToWorld() and worldToClient() are inverse transforms: pass the canvas's current bounding rectangle, not a stale size captured at mount.

Create this module beside navigation-data.ts. It adds Focus first node, Pan 80 px and Inspect canvas buttons above the canvas. Focus first node frames that node; Pan 80 px changes the camera; Inspect canvas reports the mounted scene and, where available, its actual LOD tier and governor verdict. A camera subscription updates the zoom/world-coordinate readout after gestures and plugin actions too.

CanvasPluginHost is the shared host surface used here because Angular's ready instance has no viewport property. The adapter in its tab uses the canvas's own controller, not a second camera. DiagramEngine stores engine viewport state through setViewport() and setZoom(); the sample also writes the rendered camera explicitly.

ts
import { MobilePerformanceService } from '@grafloria/engine';
import { DiagramOutlineView, EMPTY_SNAPSHOT, formatSnapshot, PerfHud, QualityGovernor } from '@grafloria/renderer';
import type { CanvasPluginHost, DiagramInstance } from '@grafloria/renderer';

export function addNavigationTools(
  host: CanvasPluginHost,
  readQuality?: () => ReturnType<DiagramInstance['getQualityState']>,
): () => void {
  const doc = host.container.ownerDocument;
  const panel = doc.createElement('div');
  const readout = doc.createElement('output');
  const details = doc.createElement('pre');
  details.style.cssText = 'height:120px;overflow:auto;margin:8px 0';
  const hudHost = doc.createElement('div');
  hudHost.style.position = 'relative';
  panel.append(readout, details, hudHost);
  host.container.before(panel);

  const mobile = new MobilePerformanceService();
  mobile.initialize();
  const hud = new PerfHud(hudHost);
  const diagnosticGovernor = new QualityGovernor();
  const outline = new DiagramOutlineView(panel, { label: 'Workflow structure' });
  const model = host.getModel();

  function updateCamera(): void {
    const rect = host.container.getBoundingClientRect();
    const box = host.viewport.getViewBox();
    const screen = host.viewport.worldToClient(box.x, box.y, rect);
    const world = host.viewport.clientToWorld(screen.x, screen.y, rect);
    readout.textContent = `Zoom ${host.viewport.getZoom().toFixed(2)}; ` +
      `visible origin (${world.x.toFixed(0)}, ${world.y.toFixed(0)}); ` +
      `device recommendation: ${mobile.getRenderQuality()}`;
  }

  function button(label: string, run: () => void): void {
    const element = doc.createElement('button');
    element.type = 'button';
    element.textContent = label;
    element.addEventListener('click', run);
    panel.insertBefore(element, readout);
  }

  button('Focus first node', () => {
    const node = model.getNodes()[0];
    if (!node) return;
    const position = node.getWorldPosition();
    const engine = host.getEngine();
    engine.setViewport({ x: position.x, y: position.y, zoom: 1.2, rotation: 0 });
    engine.setZoom(1.2);
    host.viewport.fitToBounds({
      x: position.x, y: position.y,
      width: node.size.width, height: node.size.height,
    }, 40, { maxZoom: 1.2 });
  });
  button('Pan 80 px', () => host.viewport.panByScreenDelta(80, 0));
  button('Inspect canvas', () => {
    const quality = readQuality?.();
    const snapshot = {
      ...EMPTY_SNAPSHOT,
      nodes: model.getNodes().length,
      links: model.getLinks().length,
      visibleNodes: host.container.querySelectorAll('.grafloria-svg-layer [data-node-id]').length,
      visibleLinks: host.container.querySelectorAll('.grafloria-svg-layer [data-link-id]').length,
      mountedViews: host.container.querySelectorAll('.grafloria-node-host').length,
      tier: quality?.tier ?? 'not sampled',
      governor: quality?.governor,
    };
    hud.show();
    hud.update(snapshot);
    details.textContent = formatSnapshot(snapshot).join('\n') +
      '\nTiming, dirty and routed counts are not sampled by this inspection.' +
      '\nDiagnostic governor: ' + JSON.stringify(diagnosticGovernor.getState()) +
      '\nEngine operations: ' + JSON.stringify(host.getEngine().getPerformanceReport().summary);
  });

  updateCamera();
  outline.update(model);
  const stopCamera = host.viewport.onChange(updateCamera);
  const stopNodes = model.on('node:changed', () => outline.update(model));
  const stopAdded = model.on('node:added', () => outline.update(model));
  const stopRemoved = model.on('node:removed', () => outline.update(model));
  const stopNodesCleared = model.on('nodes:cleared', () => outline.update(model));
  const stopLinks = model.on('link:added', () => outline.update(model));
  const stopLinkChanged = model.on('link:changed', () => outline.update(model));
  const stopLinkRemoved = model.on('link:removed', () => outline.update(model));
  const stopLinksCleared = model.on('links:cleared', () => outline.update(model));
  const stopSelection = model.on('selection:changed', () => outline.update(model));
  return () => {
    stopCamera();
    stopNodes(); stopAdded(); stopRemoved();
    stopNodesCleared(); stopLinksCleared();
    stopLinks(); stopLinkChanged(); stopLinkRemoved(); stopSelection();
    outline.dispose();
    hud.hide();
    panel.remove();
  };
}

Resizing the JavaScript/React/Vue/Qwik host triggers the instance's own ResizeObserver, which synchronizes the camera size. Keep a resolved host height; see container sizing. For an Angular host you resize programmatically, synchronize its live controller with syncCanvasSize(host.getBoundingClientRect()) after the size changes. The ResponsiveCanvasDirective targets an engine implementing getZoom(), getPan() and setPan(); it is not an input to DiagramCanvasComponent.

3. Support keyboard, screen readers and touch

The sample enables interaction.enableKeyboardNudge for the JavaScript, React, Vue and Qwik canvases. Select a node, then press an arrow key to move the selection one world unit; hold Shift for ten units. Ctrl, Meta and Alt prevent this nudge path. Each nudge goes through history, so Ctrl+Z or ⌘Z undoes it. Built-in keyboard handling leaves focused text inputs and editable content alone.

Angular enables keyboard navigation by default. Focus its canvas, then use Tab/Shift+Tab to move focus across nodes and links. Arrows move focus spatially when nothing is selected, or nudge the selection. C starts a keyboard connection; arrows choose a port, Tab chooses the target, Enter commits, and Escape cancels. These are Angular's bindings, not gestures you need to recreate for the other components.

The shared module adds the shipped DiagramOutlineView because a text projection gives assistive technology access to graph structure independently of what the current camera admits. Its visually hidden region contains a summary, a tree and an edge list; model subscriptions keep it current. Geometry-only changes do not rebuild its DOM. nameOf is the accompanying debug/summary helper for resolving a node id to a reader-facing name.

On the main canvas, Ctrl/⌘+wheel zooms around the pointer; an unmodified wheel pans. Shift+wheel pans horizontally in the shared renderer. On a touch screen, drag empty canvas with one finger to pan, spread two fingers to zoom in, tap a node to select it, and drag a node with one finger to move it. Keep touch-action: none on the canvas so browser page gestures do not consume the diagram's input.

Try the Keyboard & screen-reader demo and the Touch device demo. The keyboard demo owns an additional keyboard surface; its 16-pixel step is its own policy, not the shared renderer's default nudge distance.

MobilePerformanceService provides a device recommendation after initialize(): high, medium or low. The readout displays it; the service does not select the mounted renderer's tier. Use observed frame behavior, rather than device detection alone, to decide rendering policy.

4. Monitor culling, LOD and adaptive quality

Inspect canvas takes a snapshot of the current DOM and model. EMPTY_SNAPSHOT supplies the snapshot shape, formatSnapshot returns display lines, and PerfHud draws the opt-in overlay. The overlay does not intercept pointer input and is hidden from assistive technology.

This inspection counts SVG node/link elements and mounted HTML hosts. It does not measure frame time, dirty entities or rerouted links: their zero placeholders are not measurements. DOM counts may include the renderer's overscan, rather than only entities intersecting the exact visible rectangle. Inspect after panning to compare admitted entities with model totals; do not infer frame rate from those counts.

getQualityState() reports the tier actually rendered and the built-in governor's last state. Read it after a paint, not synchronously immediately after requesting a camera change. Angular's ready instance does not expose that method, so its inspection reports not sampled instead of claiming a tier.

The default LOD policy separates perception from cost: zoom determines which detail is legible; the adaptive governor determines whether the current scene can afford it.

TierZoom band without governor biasDetail
highzoom >= 1All features.
medium0.5 <= zoom < 1Labels, borders, ports, decorations, handles, routing, link detail and gradients.
sketch0.2 <= zoom < 0.5Borders, routing and link detail; no text or port chrome.
lowzoom < 0.2Plain shapes and direct lines; no optional features.

The governor is enabled by default. renderer.qualityGovernor: false in JavaScript, or rendererConfig.qualityGovernor: false in a binding, makes the tier purely zoom-derived. An options object tunes it. QualityGovernor uses rolling medians, steps down quickly, and requires sustained comfortably fast frames before recovering. Its getState() returns bias, median, samples, recovery streak and decision. Bias values are 0, 1 and 2; decisions are steady, stepped-down, stepped-up and escalated.

The separate diagnostic governor in the shared module starts with no measurements. It is not the renderer's governor and does not change the canvas. Feed record(frameMs) only real measured frame durations when you own that instrumentation; effectiveTier() applies its bias to a richest-to-poorest tier list. reset() discards its measurements after a scene swap.

For your own timed operations, PerformanceMonitor wraps a synchronous or asynchronous function with measure() and returns its result. Set enableMonitoring: true to collect metrics; monitoring defaults to off. getReport() returns per-operation counts/times and a summary. The engine's getPerformanceReport() reports its own monitor, not the renderer's paint statistics.

Compare Contextual zoom, Perf HUD & quality governor, and the Stress test. The HUD demo distinguishes governor inputs, actual scene counts and explicitly timed pan bursts; it does not equate a synthetic governor input with an observed canvas frame.

5. Use a read-only overview

If the overview belongs in your own panel rather than the component's plugin cluster, use createMiniMap with the mounted instance's camera and model. This complete JavaScript entry replaces step 1's JavaScript entry. It keeps the background and controls but disables the plugin minimap, then mounts a non-interactive overview. refresh() belongs here because a manually created minimap does not subscribe to model changes; attachCanvasPlugins() normally supplies those subscriptions.

ts
import './style.css';
import { render } from '@grafloria/element';
import { attachCanvasPlugins, createMiniMap } from '@grafloria/renderer';
import { nodes, edges, plugins } from './navigation-data';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const host = document.createElement('div');
host.style.cssText = 'height:500px;width:100%;position:relative;touch-action:none';
const close = document.createElement('button');
close.textContent = 'Close diagram';
app.replaceChildren(close, host);
const diagram = render({ nodes, edges }, host);
const attachment = attachCanvasPlugins(diagram, { ...plugins, minimap: false });
const minimap = createMiniMap(host, diagram.viewport, () => diagram.getModel(), {
  width: 170, height: 110, interactive: false, ariaLabel: 'Read-only workflow overview',
});
const model = diagram.getModel();
const disposers = [
  model.on('node:changed', () => minimap.refresh()),
  model.on('node:added', () => minimap.refresh()),
  model.on('node:removed', () => minimap.refresh()),
  model.on('selection:changed', () => minimap.refresh()),
];
close.addEventListener('click', () => {
  disposers.forEach((dispose) => dispose());
  minimap.dispose();
  attachment.dispose();
  diagram.dispose();
  host.remove();
  close.remove();
}, { once: true });

The default interactive minimap accepts pointer press/drag to pan and wheel to zoom. A read-only overview still follows camera changes but does not accept those actions.

Options and pitfalls

OptionTypeDefaultWhat it does
background, minimap, controlsboolean or the corresponding options objectOmitted/off in attachCanvasPlugins()true uses defaults; an object configures the component; false omits it. Binding plugins: true requests all three.
bindToStorebooleantrueSynchronizes plugin visibility/lock state with the engine store; false leaves visibility declarative.
background.variant'dots' | 'lines' | 'cross' | 'none''dots'Dots, grid lines, crosses, or no pattern.
background.gapnumber20Grid spacing in world units.
background.sizenumber1Dot radius or line thickness in CSS pixels.
background.colorstring'rgba(120,130,145,0.45)'Pattern color.
background.backgroundColorstringUnset/transparentColor beneath the pattern.
background.minZoomnumber0.25Hides the grid below this zoom; 0 keeps it visible.
background.idSuffixstringGeneratedPattern-id suffix for multiple diagrams on one page.
minimap.width, minimap.heightnumber200, 150Panel dimensions in pixels.
minimap.interactivebooleantrueEnables pointer pan and minimap wheel zoom.
minimap.ariaLabelstring'Diagram minimap'Accessible name of the SVG overview.
zoomnumber1Initial scale in JavaScript's render options.
minZoom, maxZoomnumber0.1, 3Camera zoom limits; the JavaScript, React, Vue and Qwik examples raise the maximum to 4. Angular's plugin controller uses 0.1 and 3.
enablePan, enableZoombooleantrueEnables canvas pan/zoom handling. Angular names wheel zoom enableMouseWheelZoom.
zoomSensitivitynumber0.1Relative wheel-zoom step in the shared renderer.
keyboardboolean or keyboard optionstrueBuilt-in handling; false disables it; an object can veto individual actions through beforeKey.
interaction.enableKeyboardNudgebooleanfalseEnables selection nudges in the shared DOM binder.

Do not rebuild the minimap's node layer on every camera change: the camera subscription already updates its rectangle. Do not call renderNow() after each pan, zoom or node edit: the mounted instance schedules the necessary paint. Use the controller's transforms for overlays rather than multiplying coordinates by zoom yourself.

Was this page helpful?