Hulian UIv0.93.5413 components0 components
  • Start
  • Components
  • Blocks
  • Pages
  • Demos
  • Changelog
ChineseEnglish
  • ComponentsComponents
  • ThemeTheme

Collections

  • QuestionCard
  • Table
  • Book3D
  • ProTable
  • PricingTable
  • JsonViewer
  • EditableTable
  • List
  • Descriptions
  • RowActions
  • Tree
  • Card
  • Carousel
  • Video
  • Audio
  • BentoGrid
  • Image
  • MagicCard
  • AnimatedList
  • Marquee
  • Sortable
  • Kanban
  • DesignCanvas
  • LayerTree
  • StageDraw
  • SlideDeck
  • PresenterView
  • ComponentPicker
  • EventStream
  • QueueLane
  • DocumentSheet
  • Novel reader
  • Scheduler
  • Org classroom
  • Danmaku
  • LiveChat
  • LivePlayer
  • LogViewer
  • FileTree
  • CodeReviewThread
  • VirtualList
  • InfiniteScroll
  • LogoLoop
  • BounceCards
  • CardSwap
  • ChromaGrid
  • CircularGallery
  • DomeGallery
  • FlyingPosters
  • InfiniteMenu
  • MagicBento
  • ScrollStack
  • ProfileCard
  • TiltedCard
  • PixelCard
  • DecayCard
  • ReflectiveCard
  • Folder

Charts and Diagrams

  • Flow
  • Diagram
  • Paper
  • SequenceDiagram
  • Sankey
  • Sparkline
  • Funnel
  • Treemap
  • Gantt
  • Heatmap
  • ContributionGraph
  • Legend
  • Chart
  • WorldMap

Information

  • ImageViewer
  • LiveProductCard
  • DiffStat
  • ScoreRing
  • ScoreScale
  • Badge
  • Dot
  • StatusDot
  • Chip
  • FilterChip
  • Coupon
  • Tag
  • Annotation
  • Avatar
  • AvatarCircles
  • User
  • QRCode
  • Comment
  • RelativeTime
  • GitCommit
  • DeployStatus
  • ShieldBadge
  • AwardBadge
  • CreditCard
  • IconTile

Metrics

  • Stat
  • Statistic
  • Meter
  • Timeline
  • NumberTicker

Placeholders

  • Empty
  • Skeleton
  • Watermark

DesignCanvas

design-canvas

Infinite 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.

Hero banner
Feature card
Call to action
tsx
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.

Hero banner
Feature card
Call to action
tsx
<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.

Locked board
Feature card
Call to action
tsx
<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.

Zoom 80%Pan 0 / 0
Hero banner
Feature card
Call to action
Board A · 320×280
tsx
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

ts
import { DesignCanvas, alignItems, canvasToScreen, distributeItems, itemsBounds, moveRect, normalizeRect, resizeRect, snapTo } from "@hulianui/ui"

Props

NameTypeDefaultDescription
itemsDesignCanvasItem[][]Controlled { id, x, y, width, height, locked?, label?, rotation?, zIndex?, groupId? } elements whose geometry the canvas owns.
zoomnumber-Controlled zoom. When present the canvas only reports onZoomChange.
defaultZoomnumber1Initial 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.
selectedElementstring | null-Controlled single selection (element id or path), compatible with multi-select API.
defaultSelectedElementstring | nullnullInitial single selection when uncontrolled.
selectedElementsstring[]-Controlled multi-select ids. Takes precedence over selectedElement.
defaultSelectedElementsstring[]-Initial multi-select ids when uncontrolled.
multiSelectboolean-Explicitly enable multi-select (Shift/Cmd toggle + marquee selection); auto-enabled when any multi-select prop is passed.
marqueebooleanFollows multi-selectWhether left-dragging on empty canvas draws a marquee box; defaults to false in single-select mode to keep empty-space drag panning.
rotatablebooleantrueShow the top rotation handle when a single unlocked item is selected.
rotationSnapnumber15Angle snap increment in degrees while holding Shift during rotation.
smartGuidesbooleanfalseAutomatically snap moving/resizing items to other items and artboard edges/centers, drawing alignment guide lines.
smartGuideThresholdnumber6Snap threshold in screen pixels for Smart Guides.
artboardDesignCanvasArtboard-Fixed artboard frame config ({ width, height, clip?, background?, label? }); fitView and smartGuides prioritize the artboard bounds.
rulersbooleanfalseRender dynamic top and left world-coordinate rulers that track pan and zoom.
minZoomnumber0.1Lower zoom bound.
maxZoomnumber4Upper zoom bound.
gridboolean | numbertrueGrid backdrop: true means 40 canvas units, a number sets the cell size, false disables it.
snapnumber0Snap step in canvas units for dragging, resizing, and arrow nudges. 0 disables snapping.
minItemSizenumber8Minimum 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.
controlsbooleantrueShow the zoom toolbar in the bottom-right corner.
readOnlybooleanfalseDisable dragging, resizing, rotation, and deletion while keeping selection, panning, and zooming.
classNamestring-Outer class name. It must have a definite height; the canvas fills it.
labelsPartial\<DesignCanvasLabels\>-Overrides the copy taken from the locale (canvas, item, zoomIn, zoomOut, fitView, resetView). Omit it and the canvas follows ConfigProvider.
apiRefMutableRefObject\<DesignCanvasApi | null\>-Imperative handle (zoomIn, zoomOut, reset, fitView, screenToCanvas, alignSelection, distributeSelection, selectAll, clearSelection).

DesignCanvasItem

NameTypeDefaultDescription
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.
lockedbooleanfalseLocked: no dragging, resize, or rotation handles, while selection and tab focus still work.
labelstringFalls back to idAccessible name.
rotationnumber0Clockwise rotation angle in degrees.
zIndexnumber-Stacking order (z-index).
groupIdstring-Optional group identifier for layer-panel synchronization.

Events

EventTypeDescription
onItemsChange(items: DesignCanvasItem[]) => voidEmits 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) => voidDelete or Backspace on the selected element. Omit it to ignore the delete keys.
onItemsDelete(ids: string[]) => voidBatch delete callback for multi-select; falls back to calling onItemDelete per id when omitted.
onSelect(elementPath: string | null) => voidSelection change: an element id, or null when the empty canvas is clicked.
onSelectionChange(ids: string[]) => voidMulti-select change callback emitting all selected element ids.
onZoomChange(zoom: number) => voidZoom change.
onPanChange(pan: { x, y }) => voidPan change.

Slots

SlotTypeDescription
renderItem(item, state: { selected, dragging, resizing, rotating }) => ReactNodeRender the element body; positioning, the selection box, and the handles belong to the canvas. Defaults to an empty placeholder frame.
childrenReactNodeFree layer mounted straight into the world-coordinate layer. It follows pan and zoom, but you place it yourself.

Example

tsx
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:

ts
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" with tabIndex=0 and a visible focus ring; its accessible name comes from labels.canvas. Copy resolves as labels prop first, then the ConfigProvider locale, then the built-in Chinese fallback.
  • Every items element is focusable and reached in order by Tab. Focusing an element selects it; selected items carry aria-current="true" plus data-selected and a focus-visible ring.
  • An element's accessible name is its label, falling back to id, 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+arrow moves ten times as far, Alt+arrow resizes, Cmd/Ctrl+A selects all in multi-select mode, and Delete or Backspace removes selected elements. Resize and rotation handles are aria-hidden pointer-only decorations.
  • When focus sits in an input, textarea, or contenteditable inside an element, arrow keys and Delete are handed back to that control instead of being hijacked by the canvas.

Usage notes

  • The outer className must have a definite height or the canvas is invisible.
  • The canvas is fully controlled: onItemsChange emits 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; read dragging, resizing, or rotating in renderItem to drive live external panels.
  • When multi-select is active (multiSelect, selectedElements, or onSelectionChange), left-dragging on empty space draws a marquee selection box by default. Use Space+drag, middle-drag, or right-drag to pan, or pass marquee={false} to restore empty-space left-drag panning.
  • The canvas does not own the geometry of anything in children. Adding data-canvas-item there 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-drag to exempt any other custom element.
  • Right-drag is part of the pan gesture, so the native context menu is suppressed. Listen for contextmenu inside renderItem and call stopPropagation to 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

PreviousSequenceDiagramData DisplayNextLayerTree

On this page

  • Usage
  • Documentation
    • When to use
    • Import
    • Props
    • Events
    • Slots
    • Example
    • Accessibility
    • Usage notes
    • Related