A lightweight, framework-agnostic infinite canvas SDK for the web — with first-class support for embedding interactive HTML elements.
html elements on the canvas (screen, minimap, and export) instead of the DOM, with typed element activation eventsgetRenderStats() and logPerformance() for frame timingnpm install @fieldnotes/core
Core is domain-agnostic. VTT-specific features (grid, fog of war, measurement, templates, tokens) live in @fieldnotes/vtt:
npm install @fieldnotes/vtt
import { Viewport } from '@fieldnotes/core';
// Mount on any container element; 'default' registers hand, select, pencil, eraser,
// arrow, note, text, shape and frame tools and activates select
const viewport = new Viewport(document.getElementById('canvas'), {
background: { pattern: 'dots', spacing: 24 },
tools: 'default',
});
// Restore and persist the board
const saved = localStorage.getItem('board');
if (saved) viewport.loadJSON(saved);
let saveTimer: ReturnType<typeof setTimeout> | undefined;
viewport.onStateChange(() => {
// Fires on every change, including each camera move; save once changes settle
clearTimeout(saveTimer);
saveTimer = setTimeout(() => localStorage.setItem('board', viewport.exportJSON()), 250);
});
// Clean up when done
viewport.destroy();
Pass tools: [...] instead (for example [...createDefaultTools(), new ImageTool()]) to
choose your own set, or register tools later with viewport.toolManager.register(tool).
Your container element needs a defined size (width/height). The canvas fills its container.
The main differentiator — embed any DOM node as a fully interactive canvas element:
const card = document.createElement('div');
card.innerHTML = '<h3>My Card</h3><button>Click me</button>';
// Buttons, inputs, links — everything works
card.querySelector('button').addEventListener('click', () => {
console.log('Clicked inside the canvas!');
});
const elementId = viewport.addHtmlElement(card, { x: 100, y: 200 }, { w: 250, h: 150 });
HTML elements pan, zoom, resize, and interleave by layer/index with canvas-rendered content. They
use a two-mode interaction model:
You can also exit interact mode programmatically:
viewport.stopInteracting();
// Programmatic
viewport.addImage('https://example.com/photo.jpg', { x: 0, y: 0 });
viewport.addImage('/assets/map.png', { x: 0, y: 0 }, { w: 800, h: 600 });
// Drag & drop is handled automatically — drop images onto the canvas
Important: Use URLs, not base64 data URLs. Images are stored inline in the serialized state. A single base64-encoded photo can be 2-5MB, which will blow past the
localStorage~5MB quota and make JSON exports impractical. Upload images to your server or CDN and use the URL. For dropped, pasted and imported images, setassets(see the ViewportOptions reference). For offline/local-first apps, store blobs in IndexedDB and reference them by URL.
// Default: a centered 100×100 rectangle
const id = viewport.addShape();
// Override shape, size, position, and colors
viewport.addShape({
shape: 'ellipse',
size: { w: 200, h: 120 },
position: { x: 0, y: 0 },
strokeColor: '#1d4ed8',
fillColor: '#dbeafe',
strokeWidth: 2,
});
addShape(opts?): string creates a shape in a single undo step, selects the new shape, and returns its id. With no options it places a 100×100 rectangle centered in the current viewport — a keyboard-friendly path to shape creation.
Export the canvas as a PNG image:
const blob = await viewport.exportImage({
scale: 2, // pixel density (default 2)
padding: 20, // world-space padding around content (default 0)
background: '#fff', // fill color
filter: (el) => el.type !== 'html', // optional per-element filter
imageTimeoutMs: 10_000, // maximum wait per image
maxDimension: 16_384, // maximum output width or height
maxPixels: 67_108_864, // maximum output pixel count
onAssetError: ({ elementId, src, reason }) => {
console.warn(`Could not export ${elementId} (${reason}): ${src}`);
},
});
frameId exports one root frame's exact content rectangle and only its descendants. It leaves out
the frame title, border, padding chrome, and unrelated overlap. Empty frames still produce exact-size
output. frameId works with exportImage() and exportSVG(). For raster export it conflicts with
region, so supplying both throws. filter, explicit background, HTML renderers and painters,
image diagnostics, registry capabilities, and render hooks still apply. Frame PNG export defaults to
transparent; JPEG retains its opaque default.
See the export guide. Remote images are
requested with anonymous CORS using their original URLs. PNG and PDF exports draw a placeholder when
an image fails; onAssetError reports cors, load, timeout, or encode, and without a callback
each failed URL logs one console.warn. exportSVG writes text, notes and labels as SVG text and
can embed font faces you supply. exportPDF resolves to a PDF with one picture page per frame, or
one for the board, and keeps element links clickable.
embedScene: true stores the exported elements in the PNG or SVG, so the file can be opened again
as a board. The scene holds every element inside the export bounds, including ones that fog or
render hooks paint over, so never embed it in an export for viewers who must not see those
elements. PDF links still point at elements under fog; pass links: false when sharing a fogged
board. readSceneFile reads the scene back, and dropping the file on a board inserts it:
const png = await viewport.exportImage({ embedScene: true });
const state = png ? await readSceneFile(png) : null;
if (state) viewport.loadState(state);
Application-owned HTML embeds require an explicit rasterization hook. Return a ready canvas-compatible image source; Field Notes applies the element's size, rotation, paint order, and layer opacity in both PNG and SVG exports:
const options = {
htmlTimeoutMs: 10_000,
renderHtml: async (element) => {
const node = document.querySelector(`[data-element-id="${element.id}"]`);
return node ? rasterizeToCanvas(node) : null; // application or library implementation
},
onHtmlError: ({ elementId, reason }) => {
console.warn(`Could not export HTML element ${elementId}: ${reason}`);
},
};
const png = await viewport.exportImage(options);
const svg = await viewport.exportSVG(options);
Without renderHtml, embeds remain omitted and can be observed through onHtmlError.
// Get a snapshot of render stats
const stats = viewport.getRenderStats();
// { fps, avgFrameMs, p95FrameMs, lastGridMs, frameCount }
// Log stats to console every 2 seconds (returns stop function)
const stop = viewport.logPerformance(2000);
// [FieldNotes] fps=60 frame=1.2ms p95=2.1ms grid=0.1ms
stop(); // stop logging
const { camera } = viewport;
camera.pan(100, 50); // pan by offset
camera.moveTo(0, 0); // jump to position
camera.setZoom(2); // set zoom level
camera.zoomAt(1.5, { x: 400, y: 300 }); // zoom toward screen point
const world = camera.screenToWorld({ x: e.clientX, y: e.clientY });
const screen = camera.worldToScreen({ x: 0, y: 0 });
camera.onChange(() => {
/* camera moved */
});
const removeConstraint = camera.addConstraint((next) => ({
...next,
zoom: Math.min(next.zoom, 2),
}));
removeConstraint();
Constraints run in registration order for every camera mutation and animation. The function
returned by addConstraint unregisters that constraint.
const presentation = createPresentationSource(viewport);
viewport.presentation.start();
viewport.presentation.next();
viewport.presentation.onChange(() => {
console.log(viewport.presentation.getState());
});
presentation.subscribe(() => renderPresentation(presentation.getSnapshot()));
start() steps through every frame on a visible layer, in scene order, unless you pass slides. Right/Down arrow, PageDown and Space go forward; Left/Up arrow, PageUp and Shift+Space go back; Home and End jump to the first and last slide; Escape exits. These keys can't be rebound. createPresentationSource(viewport) exposes the same state as a subscribe/getSnapshot source for framework stores. Give the host container an opaque background, because the fullscreen backdrop is black.
Direct access to canvas elements:
const { store } = viewport;
const all = store.getAll(); // visible scene order: layer, then depth-first hierarchy
const el = store.getById('some-id'); // includes a remote orphan retained for repair
const strokes = store.getElementsByType('stroke');
const children = store.getChildren('some-id');
const descendants = store.getDescendants('some-id');
store.update('some-id', { locked: true });
store.remove('some-id');
viewport.setParent('child-id', 'parent-id');
store.on('add', (el) => console.log('added', el));
store.on('remove', (el) => console.log('removed', el));
store.on('update', ({ previous, current }) => {
/* ... */
});
getAll, type queries, and spatial queries use the visible hierarchy projection. A remote child
whose parent has not arrived remains available through getById but is omitted from those queries.
An extension parent can define clipBounds as an axis-aligned world rectangle; it clips descendants,
and nested parent clips intersect. FrameElement is a built-in root-only parent. Frames do not nest
or rotate, and geometry alone never adds a child. Use FrameTool or createFrame() to make one:
const frame = createFrame({
position: { x: 0, y: 0 },
size: { w: 320, h: 180 },
layerId: viewport.layerManager.activeLayerId,
});
store.add(frame);
viewport.addToFrame(frame.id, [elementId]);
viewport.removeFromFrame(frame.id, [elementId]);
viewport.dissolveFrame(frame.id);
Resizing a frame keeps its children at their existing geometry. Deleting a frame deletes its subtree. Dissolving it removes the frame and preserves direct children as roots.
viewport.undo();
viewport.redo();
viewport.history.canUndo; // boolean
viewport.history.canRedo; // boolean
viewport.history.onChange(() => {
/* update UI */
});
Organize elements into named layers with visibility, lock, and ordering controls. All elements on a higher layer render above all elements on a lower layer, regardless of individual z-index.
const { layerManager } = viewport;
// Create layers
const background = layerManager.activeLayer; // "Layer 1" exists by default
layerManager.renameLayer(background.id, 'Map');
const tokens = layerManager.createLayer('Tokens');
const notes = layerManager.createLayer('Notes');
// Set active layer — new elements are created on the active layer
layerManager.setActiveLayer(tokens.id);
// Visibility and locking
layerManager.setLayerVisible(background.id, false); // hide
layerManager.setLayerLocked(background.id, true); // prevent selection/editing
// Move elements between layers
layerManager.moveElementToLayer(elementId, notes.id);
// Reorder layers
layerManager.reorderLayer(tokens.id, 5); // higher order = renders on top
// Query
layerManager.getLayers(); // sorted by order
layerManager.isLayerVisible(id);
layerManager.isLayerLocked(id);
// Listen for changes
layerManager.on('change', () => {
/* update UI */
});
Locked layers prevent selection, erasing, and arrow binding on their elements. Hidden layers are invisible and non-interactive. The active layer cannot be hidden or locked — if you try, it automatically switches to the next available layer.
// Save
const json = viewport.exportJSON();
localStorage.setItem('canvas', json);
// Load
viewport.loadJSON(localStorage.getItem('canvas'));
Note: Serialized state includes all layers and element
layerIdassignments. States saved before layers were introduced are automatically migrated — elements are placed on a default "Layer 1".
Two equivalent pairs:
exportJSON()/loadJSON()work with strings and are the canonical choice for persistence.exportState()/loadState()work with in-memoryCanvasStateobjects, skipping the JSON round-trip — this is whatAutoSaveuses. The module-levelexportState/parseStatefunctions are no longer exported; use theViewportmethods.
viewport.setTool('pencil');
viewport.setTool('hand');
viewport.toolManager.onChange((toolName) => {
console.log('switched to', toolName);
});
Defaults (remappable): Delete/Backspace delete · Escape deselect · mod+Z undo ·
mod+Y/mod+Shift+Z redo · mod+A select all · mod+C/V/D copy/paste/duplicate ·
[/] z-order (with mod = to back/front) · Shift+1 zoom-to-fit · mod+= zoom in ·
mod+- zoom out · mod+0 reset zoom to 100% · arrows nudge · tool keys V select,
H hand, P pencil, E eraser, A arrow, N note, T text, S shape, F frame, and L laser when a LaserTool is registered · mod+K opens the command palette · ? opens shortcuts help.
mod = Ctrl or Cmd. Shortcuts fire only while the canvas has focus (click it once);
pass shortcuts: { scope: 'window' } for page-wide handling.
const viewport = new Viewport(el, {
shortcuts: {
bindings: {
'edit.duplicate': 'mod+shift+d', // remap
'tool.pencil': ['p', 'b'], // multiple bindings
'edit.copy': null, // disable
'tool.my-custom-tool': 'f', // any registered tool works
},
},
});
viewport.shortcuts.rebind('edit.undo', 'mod+u');
viewport.shortcuts.disable('select.all');
viewport.shortcuts.reset(); // back to defaults
viewport.shortcuts.getBindings(); // current table (canonical ids) — render a settings UI
0.86 migration (pre-1.0):
getBindings()returns canonical map keys immediately. Legacy inputs remain temporarily accepted byViewportOptions.shortcuts.bindings,rebind/disable/reset, and actionget/run/isEnabled, but they do not preserve legacy keys in returned maps. Migrate persisted maps and key comparisons now:undo→edit.undoandtool:pencil→tool.pencil. Input aliases are removed in 0.88.0.
Every keyboard shortcut and context-menu entry is backed by a named action in the registry. Use viewport.actions to inspect, run, or extend them.
| Field | Type | Description |
|---|---|---|
id |
string |
Namespaced unique id, e.g. 'edit.undo', 'tool.pencil' |
label |
string | (ctx) => string |
Human-readable label |
keywords |
readonly string[] |
Search terms for command palette or filtering (optional) |
icon |
string |
Identifier only (e.g. 'undo'); UI layers map it to a glyph. Core never renders it (optional) |
shortcut |
readonly string[] |
Default key bindings (user rebinding overrides) (optional) |
allowShift |
boolean |
Match with or without Shift held (e.g. nudge). Default false (optional) |
menu |
{ group, order } |
Context-menu placement (omit to hide from menu) (optional) |
enabled |
(ctx) => boolean |
Guard; disabled actions are hidden from the menu (optional) |
preventDefault |
boolean |
Call preventDefault on the triggering keyboard event. Default true (optional) |
perform |
(ctx, invocation) => void | boolean |
The action body. Returning false means "nothing happened" (keyboard then leaves the browser default alone) |
viewport.actions.list(); // all registered actions
viewport.actions.run('edit.undo', { source: 'api' }); // programmatic trigger
viewport.actions.onChange(() => {
/* rebuild UI */
});
Plugins register actions through the configure context:
configure(ctx) {
ctx.registerAction({
id: 'stamp.apply',
label: 'Apply stamp',
shortcut: ['mod+shift+s'],
menu: { group: 'stamp', order: 10 },
enabled: (a) => a.selectedIds.length > 0,
perform: (a) => { /* ... */ },
});
}
New action definitions passed to
viewport.actions.register()orctx.registerAction()must use canonical ids. Recognized legacy aliases are rejected with their canonical replacement; legacy lookup and input compatibility remains available until 0.88.0.
mod+K opens the command palette. An empty query lists enabled actions with their current keys.
Typing filters actions and finds notes, text, arrow labels and frame titles, without regard to case or accents. Down and Up move through results and move the camera to the active board result. Enter runs an action or reveals a board result and closes the palette. Escape closes it. ? opens shortcuts help, which lists current bindings.
viewport.palette.open('budget');
viewport.shortcutsHelp.open();
new Viewport(el, { palette: { strings: { placeholder: 'Suche' } } });
Pass palette: false to remove the palette and help. Use --fieldnotes-palette-* custom
properties to style the dialogs. They mount in the host container with position: fixed; if that container has a CSS transform or filter, they are placed against it instead of the window.
All drawing tools support setOptions() for changing color, width, and other settings without re-creating the tool:
// Get a tool by name (type-safe with generics)
const pencil = viewport.toolManager.getTool<PencilTool>('pencil');
const arrow = viewport.toolManager.getTool<ArrowTool>('arrow');
const note = viewport.toolManager.getTool<NoteTool>('note');
// Change colors
pencil?.setOptions({ color: '#ff0000' });
arrow?.setOptions({ color: '#ff0000' });
note?.setOptions({ backgroundColor: '#e8f5e9' });
// Change stroke width
pencil?.setOptions({ width: 5 });
arrow?.setOptions({ width: 3 });
The pencil tool automatically smooths freehand strokes using Ramer-Douglas-Peucker point simplification and Catmull-Rom curve fitting. You can control the smoothing tolerance:
new PencilTool({
smoothing: 1.5, // default — higher = smoother, lower = more detail
});
// Or at runtime
pencil?.setOptions({ smoothing: 3 });
When using a stylus (Apple Pencil, Surface Pen), stroke width varies based on pressure automatically. Width scales from 0.4 × width at pressure 0 to 1.8 × width at full pressure. Input that reports pressure 0 (a mouse, or a device without pressure) is drawn at pressure 0.5, which is 1.1 × width.
Stroke points include pressure data in the StrokePoint type:
interface StrokePoint {
x: number;
y: number;
pressure: number; // 0-1
}
Implement the Tool interface to create your own tools:
import type { Tool, ToolContext, PointerState } from '@fieldnotes/core';
const myTool: Tool = {
name: 'my-tool',
onPointerDown(state: PointerState, ctx: ToolContext) {
const world = ctx.camera.screenToWorld({ x: state.x, y: state.y });
// state.pressure is available for stylus input (0-1)
},
onPointerMove(state: PointerState, ctx: ToolContext) {
// called during drag
},
onPointerUp(state: PointerState, ctx: ToolContext) {
// finalize action
ctx.store.add(myElement);
ctx.requestRender();
},
// Optional
onActivate(ctx) {
ctx.setCursor?.('crosshair');
},
onDeactivate(ctx) {
ctx.setCursor?.('default');
},
renderOverlay(canvasCtx) {
/* draw preview on canvas */
},
};
viewport.toolManager.register(myTool);
viewport.setTool('my-tool');
new Viewport(container, {
camera: {
minZoom: 0.1, // default: 0.1
maxZoom: 10, // default: 10
},
background: {
pattern: 'dots', // 'dots' | 'grid' | 'none' (default: 'dots')
spacing: 24, // grid spacing in px (default: 24)
color: '#d0d0d0', // dot/line color (default: '#d0d0d0')
},
// Called for every drop before core acts; return false to let core handle it
onDrop: (event, worldPosition) => {
/* handle drop */
},
// Called for every paste core would handle; return false to let core handle it
onPaste: (event, worldPosition) => {
if (readOnly) return true; // the host owns the paste, so nothing is inserted
return false;
},
// Uploads dropped, pasted and imported images instead of storing them as base64
assets: {
upload: async (file) => ({ src: await uploadImage(file) }), // application implementation
},
// Called when an image element fails to load; failed images render a gray
// placeholder. Falls back to console.warn when unset.
onImageError: ({ src, elementIds, reason }) => {
/* handle broken image */
},
});
camera?: CameraOptions — minZoom / maxZoom (defaults 0.1 / 10).background?: BackgroundOptions — pattern, spacing, color.fontSizePresets?: FontSizePreset[] — custom font-size steps for the note toolbar.toolbar?: boolean — show/hide the note formatting toolbar (default true).placeholder?: string — placeholder text shown in empty notes.shortcuts?: ShortcutOptions — seed the keyboard shortcut table with custom bindings (use canonical action ids like 'edit.undo', 'tool.pencil').onHtmlElementMount? — called after loadState for HTML elements that need content injected.onDrop? — called for every drop before core acts. Return false to let core handle it;
true or nothing means the host handled the drop.onPaste? — called for every paste core would handle: images, text, links, board and scene
files, and Field Notes clipboard data. Return false to let core handle it; true or nothing
means the host handled the paste. When onPaste is set, core calls preventDefault only after
it returns false.assets?: AssetResolver — upload(file, { kind }) resolves to { src } for dropped, pasted and
imported images. Without it images are stored inline as base64.onOpenLink?(link, event) — called before an element's link opens; event is null for
keyboard, menu and command palette opens. Return true to open it yourself, for example to move
to another board.onImageError? — called when an image element fails to load (reason: 'load') or its upload
fails (reason: 'upload').panBufferMargin?: number (default 256) — CSS-pixel margin cached beyond the viewport so
small pans re-composite instead of re-rasterizing the layers and grid. Larger = more pan
reuse, more memory per layer. Set 0 to disable (exact-viewport caches) on memory-tight hosts.new PencilTool({ color: '#ff0000', width: 3, smoothing: 1.5 });
new EraserTool({ radius: 30 }); // radius is screen pixels (converted to world units per zoom); mode: 'partial' (default) splits strokes at the erased span; mode: 'stroke' deletes the whole stroke
new ArrowTool({ color: '#333', width: 2 });
PencilTool also accepts opacity (0–1), blendMode ('source-over' | 'multiply'), and name — so a highlighter tool is just a named pencil variant with multiply blending:
// Register a highlighter alongside the standard pencil
viewport.toolManager.register(
new PencilTool({
name: 'highlighter',
color: '#facc15',
width: 12,
opacity: 0.4,
blendMode: 'multiply',
}),
);
viewport.setTool('highlighter');
ShapeTool supports a 'line' shape kind that draws a straight segment between two points. Hold Shift while drawing to snap to 45° increments. Lines are hit-tested by proximity to the segment, and ShapeElement.flip records which diagonal of the bounding box the line runs along. When a line is selected, it shows two endpoint drag-handles instead of bounding-box resize handles — drag one endpoint to reshape the line while the other stays anchored.
Double-click or double-tap a rectangle, ellipse, or arrow to edit its text. Select one and press Enter to run the selection.edit-text action. See Tools and input for the full interaction rules. Rectangles and ellipses grow for their text, do not shrink automatically, and cannot resize below the text's height. Arrow labels are text elements positioned at the curve midpoint. Arrows never grow.
createBoundText(container, options) creates the text child. viewport.setBoundText(id, html)
creates, updates, or removes one and keeps the text change and any container growth in one undo
step. getBoundText and isBoundTextContainer read the relation. The child has wrap and
autoResize; wrapping uses the container's text box, and autoResize controls whether free text
shrinks to its content while editing. measureText measures text for a host's own layout.
The third createBoundText argument defaults to the global registry; private extensions should pass viewport.elementRegistry.
An extension element definition can implement boundTextLayout(el), returning the text box and an optional grow(el, height) that returns the element grown to fit. setBoundText adds the child and any growth as one undo step; if you add the child with store.add instead, wrap the call in viewport.transaction.
ArrowElement.label and the label option of createArrow are deprecated; use setBoundText.
Loading a board turns each label into a text element on its arrow, and the next save stores that
element instead.
Create an elbow arrow with routing: 'elbow'. fixedSegments pins a vertical segment at an x
value or a horizontal segment at a y value. An arrow accepts up to
MAX_ARROW_FIXED_SEGMENTS pins. resetArrowRoute removes the pins in one undo step.
const arrow = createArrow({
from: { x: 0, y: 0 },
to: { x: 240, y: 160 },
routing: 'elbow',
fixedSegments: [{ axis: 'x', value: 120 }],
});
viewport.store.add(arrow);
viewport.resetArrowRoute(arrow.id);
An elbow route uses visible nearby shapes and bounded search. If its search cannot find a route, the arrow draws its authored orthogonal path, which can cross a shape. Readers with different visible elements can see different detours. Bound labels use the authored path, so a label can sit away from a local detour.
Old clients draw the bezier approximation and preserve elbow fields while editing existing arrows.
An old client that reconstructs an arrow with createArrow can drop routing and
fixedSegments.
Undo restores local gesture fields without reverting external edits received during that gesture. Cancelling an arrow endpoint, curved midpoint, or elbow segment handle restores its own fields and keeps external edits.
When an external container geometry update arrives during a gesture, a bound label can retain its last local layout until an authoritative label or layout update arrives. Direct-store hosts provide that update. Label geometry edits made locally in that transaction are not recorded as a separate undo step; text and style edits remain undoable.
const arrow = createArrow({ from: { x: 0, y: 0 }, to: { x: 200, y: 0 } });
viewport.store.add(arrow);
viewport.setBoundText(arrow.id, 'depends on');
new NoteTool({ backgroundColor: '#fff9c4', size: { w: 200, h: 150 } });
new ImageTool({ size: { w: 400, h: 300 } });
All elements share a base shape:
interface BaseElement {
id: string;
type: string;
position: { x: number; y: number };
index: string; // fractional order key; pass '' to factories to place on top
version: number; // bumped by the store on every local update
editor?: string; // set by sync
locked: boolean;
layerId: string;
}
| Type | Key Fields |
|---|---|
stroke |
points: StrokePoint[], color, width, opacity |
note |
size, text, backgroundColor, textColor |
arrow |
from, to, bend, routing, fixedSegments, color, width, fromBinding, toBinding |
image |
size, src |
shape |
size, shape (rectangle | ellipse | line), strokeColor, fillColor, flip (boolean — which bbox diagonal a line runs along) |
text |
size, text, fontSize, color, textAlign |
html |
size |
Custom element types, plugins, render hooks, and services are covered in Extending Field Notes.
An element type definition can provide searchText for the text that board search matches.
A normalized ElementStyle interface lets you read and apply visual properties across all element types through a single, consistent shape. The SelectTool emits a selection-change event; Viewport exposes four methods that together cover reactive UIs.
ElementStyle interfaceinterface ElementStyle {
color?: string; // stroke color / text color
fillColor?: string; // fill / background color
strokeWidth?: number; // line width in world-space units
opacity?: number; // 0–1
fontSize?: number; // px
}
ElementStyle field |
stroke |
arrow |
shape |
note |
text |
|---|---|---|---|---|---|
color |
color |
color |
strokeColor |
textColor |
color |
fillColor |
— | — | fillColor |
backgroundColor |
— |
strokeWidth |
width |
width |
strokeWidth |
— | — |
opacity |
opacity |
— | — | — | — |
fontSize |
— | — | — | (via toolbar) | fontSize |
import { styleToPatch, getElementStyle } from '@fieldnotes/core';
// ElementStyle → element-specific patch object
const patch = styleToPatch(element, { color: '#e00', strokeWidth: 3 });
store.update(element.id, patch);
// element → normalized ElementStyle
const style = getElementStyle(element);
viewport.getSelectedIds() — returns the current selection as a referentially-stable array (the same array reference is reused across calls when the selection has not changed — safe for useSyncExternalStore equality checks).viewport.onSelectionChange(listener) — subscribes to selection changes; returns an unsubscribe function. The listener receives the new stable id array.viewport.getSelectionStyle() — returns an ElementStyle containing only the properties that are identical across every selected element. Properties that differ are omitted.viewport.applyStyleToSelection(style) — applies the given ElementStyle to all selected elements in a single undo step.SelectTool.onSelectionChangeconst selectTool = viewport.toolManager.getTool<SelectTool>('select');
selectTool?.onSelectionChange((ids) => {
console.log('selected:', ids);
});
// Apply a red stroke to everything currently selected — one undo step
viewport.applyStyleToSelection({ color: '#ff0000' });
// Read back the shared style for a UI color picker
const style = viewport.getSelectionStyle();
// style.color is defined only if all selected elements share the same color
// React to selection changes
const unsub = viewport.onSelectionChange((ids) => {
setSelectedIds(ids); // ids is referentially stable — safe for deps arrays
});
// call unsub() to unsubscribe
Two methods on Viewport let you snap or space selected elements in one undo step.
viewport.alignSelection(edge): edge: AlignEdge = 'left' | 'center-x' | 'right' | 'top' | 'middle' | 'bottom'; aligns unlocked selected roots to the corresponding edge or center of their bounding box. Locked selected roots are ignored for bounds and eligibility. Needs 2+ unlocked roots.viewport.distributeSelection(axis): axis: DistributeAxis = 'horizontal' | 'vertical'; evenly spaces unlocked selected roots' centers along the axis. Locked selected roots are ignored for bounds and eligibility. Needs 3+ unlocked roots.viewport.alignSelection('left'); // flush left edges
viewport.alignSelection('center-x'); // center on vertical axis
viewport.alignSelection('middle'); // center on horizontal axis
viewport.distributeSelection('horizontal'); // equal horizontal spacing
Call viewport.setSmartGuides(true) to enable drag-time alignment snapping. While dragging a selection, its edges and centers snap to the edges and centers of nearby visible elements (within 6 screen pixels), and guide lines are drawn at each matched alignment. The result is still committed as a single undo step.
viewport.setSmartGuides(true); // enable
viewport.setSmartGuides(false); // disable (default)
Group elements so they select, move, delete, z-order, and align as a single unit.
viewport.groupSelection() — groups the current selection under a new id.viewport.ungroupSelection() — dissolves any groups in the current selection.Each is one undo step. Selecting any member selects its whole group, so to edit a single member individually, ungroup first. Pasting or duplicating a group keeps the copies grouped under a fresh id.
viewport.groupSelection(); // Ctrl/Cmd+G
viewport.ungroupSelection(); // Ctrl/Cmd+Shift+G
The shortcuts are rebindable as arrange.group and arrange.ungroup.
Select a single element and a rotate handle appears above the selection box. Drag it to rotate the element about its center; hold Shift to snap to 15° increments. Notes, text, images, HTML embeds, shapes, and strokes can all be rotated.
Hit-testing, marquee selection, and resize are all rotation-aware: resizing a rotated element keeps the opposite corner fixed in the element's local frame. Rotation is reflected in PNG export and round-trips through serialization (rotation? on elements, stored in radians).
Right-click (desktop) or touch long-press (tablet) opens a context menu over the canvas with Cut/Copy/Paste/Duplicate/Delete, z-order (to front / forward / backward / to back), Lock/Unlock, and Add link, Remove link and Open link. The menu is core-provided (plain DOM) and selects the element under the pointer if it isn't already selected. Opt out with new Viewport(el, { contextMenu: false }).
Lock with viewport.toggleLockSelection() or Ctrl/Cmd+Shift+L; a lock badge appears on the selection. Locked elements stay selectable but can't be moved, resized, or rotated. Ctrl/Cmd+X cuts the selection. The shortcuts are rebindable as arrange.toggle-lock and edit.cut.
You can drive any menu action programmatically with viewport.runAction(name) (e.g. 'edit.cut', 'edit.paste', 'arrange.toggle-lock'). It returns whether the action ran. You can also use the actions API: viewport.actions.run('edit.cut', { source: 'api' }). viewport.canPaste() reports whether the board's in-memory clipboard holds copied elements; it doesn't read the system clipboard.
| Input | Action |
|---|---|
| Scroll wheel | Zoom |
| Middle-click drag | Pan |
| Space + drag | Pan |
| Two-finger pinch | Zoom |
| Two-finger drag | Pan |
| Delete / Backspace | Remove selected |
| Ctrl+Z / Cmd+Z | Undo |
| Ctrl+Shift+Z / Cmd+Y | Redo |
| Double-click note | Edit text |
| Double-click HTML | Enter interact mode |
| Escape | Exit interact mode |
Peers can watch a pencil or highlighter stroke while it is drawn. PencilTool.onPreview emits a
preview at most every 50 ms with the stroke's last 120 points, keyed by the id the committed stroke
will have. RemoteStrokeOverlay draws remote previews on the overlay and drops each one when that
stroke is added to the store, the sender cancels, 3 s pass without an update, or remove(sender)
runs. Wire onPreview on every PencilTool instance, the highlighter included. Wire it like the
laser, for example with a SyncClient:
import { PencilTool, RemoteStrokeOverlay, toStrokePreviewPresence } from '@fieldnotes/core';
const overlay = new RemoteStrokeOverlay(viewport);
const pencil = viewport.toolManager.getTool('pencil');
if (pencil instanceof PencilTool) {
pencil.onPreview((preview) => client.sendPresence(toStrokePreviewPresence(preview)));
}
client.onPresence((from, data) => overlay.apply(from, data));
client.onPresenceLeave((from) => overlay.remove(from));
// later: overlay.dispose();
Presence is not filtered by audience on the hub. Do not forward previews for strokes on audience-restricted layers.
Works in all modern browsers supporting Pointer Events API and HTML5 Canvas.
@fieldnotes/core and @fieldnotes/react are versioned independently. The react
package's peerDependencies declare the compatible core range. Pre-1.0, minor
versions may contain breaking changes. The core peer range is bounded at the next major rather than per-minor; if a core minor
ever breaks the wrapper, a coordinated react release raises the lower bound.
MIT