ScribbleSVG

DiagramCanvas

Interactive scribble diagram editor for React

DiagramCanvas is the interactive editor: pan, zoom, shapes, arrows/lines, resize, and text. Hold Shift while drawing an arrow or line to snap to 22.5° steps. The pencil draws freehand strokes and stays active between strokes. While it's active, a toggle beside it switches smoothing on or off: smoothing evens out hand wobble but keeps deliberate corners sharp, so detailed drawings keep their shape. Smoothing starts on each time the editor mounts. Press Escape mid-stroke to drop the stroke. Standalone text selection and resize follow live glyph metrics so bounds stay tight after font-size changes. Import the bundled CSS once in your CMS or admin app.

import "@scribblesvg/react-utils/editor.css";
import { useState } from "react";
import { DiagramCanvas } from "@scribblesvg/react-utils/editor";
import type { DiagramIcon } from "@scribblesvg/react-utils/icons";
import { EMPTY_DOCUMENT, type DiagramDocument } from "@scribblesvg/core";

const icons: DiagramIcon[] = [
  {
    iconId: "server",
    label: "Server",
    svg: `<svg viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="6" /></svg>`,
  },
];

function Editor() {
  const [document, setDocument] = useState<DiagramDocument>(EMPTY_DOCUMENT);

  return (
    <div className="diagram-editor-panel">
      <DiagramCanvas
        initialDocument={document}
        onChange={setDocument}
        icons={icons}
      />
    </div>
  );
}

Layout

The editor fills its container (height: 100%). Give it a bounded height with your own class — on a wrapper or on DiagramCanvas via className:

.diagram-editor-panel {
  height: 600px;
}
<div className="diagram-editor-panel">
  <DiagramCanvas onChange={save} />
</div>

<DiagramCanvas className="diagram-editor-panel" onChange={save} />

Zoom

Scroll or pinch to zoom at the cursor. The zoom card in the bottom-right corner of the canvas has:

  • a slider from 10% to 500% on a log scale, with a soft stop at 100%
  • Zoom to fit, which frames all content (it zooms out to fit, but never in past 100%)
  • a reset button showing the current zoom; it is highlighted whenever zoom isn't 100%, and a click returns to 100%

The slider and buttons zoom around the centre of the canvas. The same actions have keys:

KeyAction
Ctrl/⌘ + + (or =)Zoom in to the next step (10, 25, 50, 75, 100, 150, 200, 300, 400, 500%)
Ctrl/⌘ + -Zoom out to the previous step
Shift + 1Zoom to fit
Shift + 0Reset to 100%

Shift + 1 and Shift + 0 are matched by physical key, so they work on layouts where Shift + 1 types another character. Ctrl/⌘ + +/- only zoom the canvas while it has focus; elsewhere they zoom the page as usual.

Pass fitOnLoad to frame the initial document when the editor mounts, instead of using the viewport saved in the document.

<DiagramCanvas initialDocument={document} fitOnLoad />

fitViewport(bounds, size, { padding }) is exported from @scribblesvg/react-utils/editor if you want to compute a fitted viewport yourself, for example with getContentBounds from @scribblesvg/core. The zoom limits are exported as MIN_ZOOM and MAX_ZOOM.

The viewport (pan and zoom) is saved in the document and reported through onChange, but it is not part of undo history.

Keyboard and focus

Shortcuts (undo/redo, copy/cut/paste, Delete, group/ungroup, Space-pan, Shift-snap, text size, zoom, Escape, ? for the shortcuts panel) only reach the editor while focus is inside it. Keys typed elsewhere on your page, such as in a form field or in a second editor, never change the diagram.

  • The canvas is focusable (tabIndex={0}) and shows a focus ring only for keyboard focus (:focus-visible).
  • Pressing anywhere in the editor, including toolbar buttons and the zoom card, gives the canvas focus. Tabbing to a toolbar button leaves focus on the button; shortcuts still work there, except Space and Enter, which press the button.
  • Text fields keep all their keys: the inline text editor, and any input, textarea, select or contenteditable you render inside the editor.
  • When focus leaves the editor, the selection is cleared, and a held Space (pan) or Shift (snap) is released so it can't stay stuck on. Switching to another window or tab keeps the selection.
  • Pinch and Ctrl/⌘ + scroll zoom work without focus.

Pass autoFocus to focus the canvas on mount, so shortcuts work before the first click. Use it when the editor is the main thing on the page; leave it off when the editor sits among other content, since it takes focus from the rest of the page.

<DiagramCanvas autoFocus onChange={save} />

Groups

Group elements to select, move and scale them as one. A group is stored as a shared groupId on its members (see Document model).

ActionResult
Ctrl/⌘ + G with two or more selectedGroup them; any groups among them merge into one
Ctrl/⌘ + Shift + GUngroup everything selected
Click a memberSelect the whole group
Double-click a member while its group is selectedSelect only that member
Click it againEdit its text
Shift + click a memberAdd or remove the whole group
Box select touching any memberSelect the whole group

A selected group is drawn as one object: a single box with corner handles, without a box around each member. When the selection holds more than one object (several groups, or a group with loose elements), each group gets one dashed box and each loose element its own, inside the selection box.

Grouping and ungrouping are one undo step each. When they would change nothing (one element selected, or the selection is already one group), the key is left to the browser. Pasting a group makes a new group, separate from the one copied.

Icons

Documents store only iconId on icon elements. Pass the matching icons array so artwork can resolve. Unresolved ids render a dashed “Missing icon” placeholder.

Treat catalog SVG as trusted host input (your bundled pack or admin-curated markup). Do not put end-user-uploaded SVG strings into icons without sanitizing first.

Persistence

Use onChange to keep the document in sync (e.g. save to your backend). The document is plain JSON from @scribblesvg/core — see Document model.

Direct reducer placement

For direct reducer consumers, PLACE_ELEMENT adds an element, selects it and switches to the select tool in one undoable transition. With select: false it clears the selection and keeps the tool instead, as the pencil does for each stroke. INSERT_IMAGE shares that placement logic after fitting and validating the image. SELECT_ELEMENT selects an existing id and switches tools without changing the document or adding history. Creation and subsequent size/text updates can share a BEGIN_HISTORY / END_HISTORY group. CANCEL_HISTORY drops an open group instead: the elements and selection go back to how they were at BEGIN_HISTORY, and no undo step is left.

Images

Pass onRequestImage to DiagramCanvas to show the Image toolbar button. Return a promise resolving to { src, alt? }, or null to cancel. The editor loads and measures the image, then inserts it in the viewport and selects it.

src is stored in the document as-is, so only these forms are accepted:

  • absolute http: or https: URLs
  • relative or root-relative paths (photo.png, /uploads/photo.png)
  • inline data:image/… URIs

Anything else, such as blob: or javascript: URLs, is ignored and nothing is inserted. For a local file, upload it and return its URL, or read it as a data: URI. Sources containing tabs, newlines or leading/trailing spaces are also rejected, so remove line breaks from base64 data first.

Dragging an image's corner handle keeps its aspect ratio. Hold Shift to stretch it freely. The edge handles always stretch one side.

Direct interaction helpers

DiagramCanvas owns drag and resize sessions in its Gesture. Direct consumers should replace the removed useElementDrag and useElementResize hooks with the pure helpers exported from @scribblesvg/react-utils/editor:

  • startDrag(elements, ids, point) returns a DragSession; dragPatches(session, point) computes position patches from its original snapshots.
  • startResize(elements, id, handle, point) and startGroupScale(elements, ids, handle, point) return a ResizeSession, or null when the target is unavailable.
  • resizePatches(session, point, freeAspect, measureText) computes size patches; freeAspect defaults to false. The optional fourth argument measures text with your host's font; the default uses core text metrics.

Store a drag session in { type: "dragging", ...session, pendingEdit: null } or a resize session in { type: "resizing", ...session }. Dispatch BEGIN_HISTORY on start, UPDATE_ELEMENTS with the patches and reanchor: true on moves, and END_HISTORY on release. Bound connectors are re-anchored in the same reducer transition; release needs no extra endpoint updates. The exported Gesture, DragSession and ResizeSession types describe the stored data; isDragging and isResizing are replaced by checking the gesture's type.

Direct connector previews

useArrowCreation(elements, dispatch, snapThreshold?) derives its preview from the current elements and stored start, pointer and Shift inputs. Existing arrowStart, previewStart, previewEnd, handleArrowClick, updatePreview and cancelArrow returns remain available; setShiftSnap(boolean) updates the constraint without moving the pointer. The optional third argument supplies the current canvas-space snapping threshold (for example, screen pixels divided by zoom); without it, the latest updatePreview threshold is used. Direct consumers should cancel creation when leaving connector tools, as useCanvasInteraction does.

On this page