DesignCanvas
design-canvasInfinite pan-and-zoom canvas with artboard frames, rulers, multi-select, rotation, smart guides, and eight-way resize.
Usage
Basic usage
Controlled items: drag to move, drag any of the eight handles to resize, click empty space to deselect; Tab walks between elements, arrow keys nudge, Delete removes.
const [items, setItems] = useState(initial);
const [selected, setSelected] = useState<string | null>("hero");
<div className="h-[360px] w-full overflow-hidden rounded border border-border">
<DesignCanvas
items={items}
onItemsChange={setItems}
selectedElement={selected}
onSelect={setSelected}
onItemDelete={(id) => setItems((p) => p.filter((i) => i.id !== id))}
renderItem={(item) => <div className="h-full w-full …">{item.label}</div>}
/>
</div>Grid snapping
grid draws the backdrop and snap sets the step; they are independent, so you can draw without snapping, or snap to a step finer than the backdrop.
<DesignCanvas items={items} onItemsChange={setItems} grid={20} snap={20} … />Locked element
A locked element can still be selected and reached with Tab, but it cannot be dragged and shows no resize handles.
<DesignCanvas
items={[{ id: "hero", x: 40, y: 32, width: 260, height: 120, locked: true }, …]}
onItemsChange={setItems}
/>Controlled viewport + custom layer
Controlling zoom / pan lets an external toolbar drive the canvas; children mount straight into the world layer, following pan and zoom while owning their own geometry.
const [zoom, setZoom] = useState(0.8);
const [pan, setPan] = useState({ x: 0, y: 0 });
<DesignCanvas
items={items}
onItemsChange={setItems}
zoom={zoom}
onZoomChange={setZoom}
pan={pan}
onPanChange={setPan}
>
<div className="pointer-events-none absolute left-[40px] top-[8px] text-[10px] text-muted-foreground">
Board A · 320×280
</div>
</DesignCanvas>When to use
Use DesignCanvas to arrange, rotate, and align rectangles on an infinite surface or a fixed-size artboard (such as a 1920×1080 presentation slide): page drafts, slide editors, boards, poster layouts, and low-code visual editors. Position, size, and rotation are the data; there is no node-edge topology.
- To orchestrate nodes and edges (AI workflows, DAGs, flowcharts) use Flow.
- To scale one fixed design size to fill a container (big-screen dashboards or slide playback) use FitScreen or SlideDeck.
- Pair with LayerTree and InspectorPanel for a complete visual editor triad.
- For cards moving between columns use Kanban; for one reorderable list use Sortable.
DesignCanvas reuses Flow's viewport math (screenToCanvas, zoomAtPoint, clampZoom), so both canvases share the same wheel feel and coordinate convention.
Import
import { DesignCanvas, alignItems, canvasToScreen, distributeItems, itemsBounds, moveRect, normalizeRect, resizeRect, snapTo } from "@hulianui/ui"Props
| Name | Type | Default | Description |
|---|---|---|---|
| items | DesignCanvasItem[] | [] | Controlled { id, x, y, width, height, locked?, label?, rotation?, zIndex?, groupId? } elements whose geometry the canvas owns. |
| zoom | number | - | Controlled zoom. When present the canvas only reports onZoomChange. |
| defaultZoom | number | 1 | Initial zoom when uncontrolled. |
| pan | { x, y } | - | Controlled pan: the screen-pixel offset of the canvas origin inside the container. |
| defaultPan | { x, y } | { x: 0, y: 0 } | Initial pan when uncontrolled. |
| selectedElement | string | null | - | Controlled single selection (element id or path), compatible with multi-select API. |
| defaultSelectedElement | string | null | null | Initial single selection when uncontrolled. |
| selectedElements | string[] | - | Controlled multi-select ids. Takes precedence over selectedElement. |
| defaultSelectedElements | string[] | - | Initial multi-select ids when uncontrolled. |
| multiSelect | boolean | - | Explicitly enable multi-select (Shift/Cmd toggle + marquee selection); auto-enabled when any multi-select prop is passed. |
| marquee | boolean | Follows multi-select | Whether left-dragging on empty canvas draws a marquee box; defaults to false in single-select mode to keep empty-space drag panning. |
| rotatable | boolean | true | Show the top rotation handle when a single unlocked item is selected. |
| rotationSnap | number | 15 | Angle snap increment in degrees while holding Shift during rotation. |
| smartGuides | boolean | false | Automatically snap moving/resizing items to other items and artboard edges/centers, drawing alignment guide lines. |
| smartGuideThreshold | number | 6 | Snap threshold in screen pixels for Smart Guides. |
| artboard | DesignCanvasArtboard | - | Fixed artboard frame config ({ width, height, clip?, background?, label? }); fitView and smartGuides prioritize the artboard bounds. |
| rulers | boolean | false | Render dynamic top and left world-coordinate rulers that track pan and zoom. |
| minZoom | number | 0.1 | Lower zoom bound. |
| maxZoom | number | 4 | Upper zoom bound. |
| grid | boolean | number | true | Grid backdrop: true means 40 canvas units, a number sets the cell size, false disables it. |
| snap | number | 0 | Snap step in canvas units for dragging, resizing, and arrow nudges. 0 disables snapping. |
| minItemSize | number | 8 | Minimum element width and height in canvas units. |
| wheelBehavior | "zoom" | "pan" | "pan" | Wheel action when no modifier is held. Ctrl (including trackpad pinch) always zooms and ignores this prop. |
| controls | boolean | true | Show the zoom toolbar in the bottom-right corner. |
| readOnly | boolean | false | Disable dragging, resizing, rotation, and deletion while keeping selection, panning, and zooming. |
| className | string | - | Outer class name. It must have a definite height; the canvas fills it. |
| labels | Partial\<DesignCanvasLabels\> | - | Overrides the copy taken from the locale (canvas, item, zoomIn, zoomOut, fitView, resetView). Omit it and the canvas follows ConfigProvider. |
| apiRef | MutableRefObject\<DesignCanvasApi | null\> | - | Imperative handle (zoomIn, zoomOut, reset, fitView, screenToCanvas, alignSelection, distributeSelection, selectAll, clearSelection). |
DesignCanvasItem
| Name | Type | Default | Description |
|---|---|---|---|
| id * | string | - | Unique key, also the value used by selectedElement and selectedElements. |
| x / y | number | - | Top-left position in canvas coordinates. |
| width / height | number | - | Size in canvas units. |
| locked | boolean | false | Locked: no dragging, resize, or rotation handles, while selection and tab focus still work. |
| label | string | Falls back to id | Accessible name. |
| rotation | number | 0 | Clockwise rotation angle in degrees. |
| zIndex | number | - | Stacking order (z-index). |
| groupId | string | - | Optional group identifier for layer-panel synchronization. |
Events
| Event | Type | Description |
|---|---|---|
| onItemsChange | (items: DesignCanvasItem[]) => void | Emits the whole new array after a geometry change. Drag, resize, and rotate commit once on pointer up; arrow keys commit on every press. |
| onItemDelete | (id: string) => void | Delete or Backspace on the selected element. Omit it to ignore the delete keys. |
| onItemsDelete | (ids: string[]) => void | Batch delete callback for multi-select; falls back to calling onItemDelete per id when omitted. |
| onSelect | (elementPath: string | null) => void | Selection change: an element id, or null when the empty canvas is clicked. |
| onSelectionChange | (ids: string[]) => void | Multi-select change callback emitting all selected element ids. |
| onZoomChange | (zoom: number) => void | Zoom change. |
| onPanChange | (pan: { x, y }) => void | Pan change. |
Slots
| Slot | Type | Description |
|---|---|---|
| renderItem | (item, state: { selected, dragging, resizing, rotating }) => ReactNode | Render the element body; positioning, the selection box, and the handles belong to the canvas. Defaults to an empty placeholder frame. |
| children | ReactNode | Free layer mounted straight into the world-coordinate layer. It follows pan and zoom, but you place it yourself. |
Example
const [items, setItems] = useState<DesignCanvasItem[]>([
{ id: "hero", x: 40, y: 32, width: 260, height: 120, label: "Hero banner", zIndex: 1 },
{ id: "cta", x: 40, y: 176, width: 120, height: 96, label: "Call to action", rotation: 0, zIndex: 2 },
]);
const [selectedIds, setSelectedIds] = useState<string[]>(["hero"]);
<div className="h-[420px] w-full overflow-hidden rounded border border-border">
<DesignCanvas
items={items}
onItemsChange={setItems}
selectedElements={selectedIds}
onSelectionChange={setSelectedIds}
onItemsDelete={(ids) => setItems((p) => p.filter((i) => !ids.includes(i.id)))}
smartGuides
rulers
artboard={{ width: 960, height: 540, label: "Slide 1 · 16:9", clip: false }}
renderItem={(item, s) => (
<div className={cn("grid h-full w-full place-items-center rounded-[var(--radius)] border bg-surface",
s.selected ? "border-primary" : "border-hairline")}>
{item.label}
</div>
)}
/>
</div>The geometry and layout helpers stand alone, which makes external toolbars (align, distribute, bulk offset) straightforward:
const aligned = alignItems(items, selectedIds, "center", { x: 0, y: 0, width: 1920, height: 1080 });
const spaced = distributeItems(items, selectedIds, "horizontal");
const bounds = itemsBounds(items);
const next = moveRect(item, 0, 8, 8);Accessibility
- The canvas is
role="application"withtabIndex=0and a visible focus ring; its accessible name comes fromlabels.canvas. Copy resolves aslabelsprop first, then the ConfigProvider locale, then the built-in Chinese fallback. - Every
itemselement is focusable and reached in order by Tab. Focusing an element selects it; selected items carryaria-current="true"plusdata-selectedand afocus-visiblering. - An element's accessible name is its
label, falling back toid, so prefer readable ids such as"hero"over"a1f3". - The keyboard path is complete: arrow keys move by one canvas unit (or by the snap step),
Shift+arrowmoves ten times as far,Alt+arrowresizes,Cmd/Ctrl+Aselects all in multi-select mode, and Delete or Backspace removes selected elements. Resize and rotation handles arearia-hiddenpointer-only decorations. - When focus sits in an
input,textarea, orcontenteditableinside an element, arrow keys and Delete are handed back to that control instead of being hijacked by the canvas.
Usage notes
- The outer
classNamemust have a definite height or the canvas is invisible. - The canvas is fully controlled:
onItemsChangeemits the whole new array, and skipping the state write snaps elements back. Drag, resize, and rotate only touch an internal draft and do not emit per frame; readdragging,resizing, orrotatinginrenderItemto drive live external panels. - When multi-select is active (
multiSelect,selectedElements, oronSelectionChange), left-dragging on empty space draws a marquee selection box by default. Use Space+drag, middle-drag, or right-drag to pan, or passmarquee={false}to restore empty-space left-drag panning. - The canvas does not own the geometry of anything in
children. Addingdata-canvas-itemthere buys selection only, never dragging, resizing, or a selection box. - Buttons and inputs inside an element work normally: pressing one selects without starting a drag. Add
data-no-dragto exempt any other custom element. - Right-drag is part of the pan gesture, so the native context menu is suppressed. Listen for
contextmenuinsiderenderItemand callstopPropagationto provide your own. - Wheel events are registered with
{ passive: false }and prevented, so the canvas never scrolls an ancestor. - Pointer Events make the component client-only.
Related
LayerTree · InspectorPanel · Flow · FitScreen · SlideDeck · Kanban · Sortable