Documentation

DraftX API Manual

Reference manual for the DraftX API, document model, methods, and events.

DraftX API Manual

Overview

This manual is the reference for the DraftX widget API.

It covers:

  • constructor options
  • methods
  • events
  • document schema
  • shape schema

For interactive examples, open the DraftX Playpen.

Constructor

new DraftX(options)

Creates and mounts a widget instance.

const widget = new DraftX({
  container: '#draftx-host',
  showGrid: true,
  snapToGrid: true,
  theme: 'light',
});

Options

interface DraftXOptions {
  container: string | HTMLElement;
  document?: DraftXDocument;
  showGrid?: boolean;
  snapToGrid?: boolean;
  theme?: DraftXTheme;
}

Container

Field: container

Required.

Accepts:

  • a CSS selector string
  • an HTMLElement

Document

Field: document

Optional initial document.

Show Grid

Field: showGrid

Optional initial grid visibility.

Snap To Grid

Field: snapToGrid

Optional initial snap state.

Theme

Field: theme

Optional initial theme.

Allowed values:

  • 'light'
  • 'dark'

Lifecycle

destroy(): void

Destroys the widget instance.

newDrawing(): void

Replaces the current drawing with an empty document.

Document Methods

setDocument(document: DraftXDocument): void

Replaces the current document using an object.

getDocument(): DraftXDocument

Returns the current document.

loadDocument(json: string): void

Parses and loads a document from JSON text.

Throws if the JSON is invalid or does not match the DraftX document schema.

saveDocument(pretty?: boolean): string

Returns the current document as JSON text.

Behavior:

  • pretty defaults to true
  • true uses two-space indentation
  • false returns compact JSON

View Methods

zoomIn(): void

Zooms in.

zoomOut(): void

Zooms out.

resetView(): void

Resets the current view.

fitToView(): void

Fits the current document into view.

getView(): DraftXView

Returns:

interface DraftXView {
  center: DraftXPoint;
  zoom: number;
}

focusShapeInView(id: string): boolean

Attempts to focus the given shape in view.

Returns:

  • true if the shape was found and focused
  • false otherwise

Appearance Methods

setTheme(theme: DraftXTheme): void

Sets the theme.

Allowed values:

  • 'light'
  • 'dark'

getTheme(): DraftXTheme

Returns the active theme.

setHighlightColor(color: string): void

Sets the widget highlight color.

Accepted format:

  • #rgb
  • #rrggbb

Examples:

  • #0fd
  • #0f6d5f

getGridVisible(): boolean

Returns the current grid visibility.

setGridVisible(visible: boolean): void

Shows or hides the grid.

getSnapToGrid(): boolean

Returns the current snap setting.

setSnapToGrid(enabled: boolean): void

Enables or disables snap-to-grid.

Tool Methods

setTool(tool: DraftXTool): void

Allowed tools:

  • 'select'
  • 'rect'
  • 'ellipse'
  • 'line'
  • 'text'

getTool(): DraftXTool

Returns the active tool.

Selection And Editing Methods

selectShape(id: string | null): void

Selects one shape by id.

Pass null to clear the current selection.

selectShapes(ids: readonly string[]): void

Selects multiple shapes.

copySelection(): void

Copies the current selection into the widget clipboard.

pasteSelection(): void

Pastes the clipboard using the default offset.

pasteSelection(point: DraftXPoint): void

Pastes the clipboard at the provided world point.

interface DraftXPoint {
  x: number;
  y: number;
}

moveSelection(dx: number, dy: number): void

Moves the current selection by the given delta.

resizeSelection(rect: DraftXSelectionRect): void

Resizes the current selection to the provided bounds.

interface DraftXSelectionRect {
  x1: number;
  y1: number;
  x2: number;
  y2: number;
}

rotateSelection(angleDelta: number): void

Rotates the current selection.

deleteSelection(): void

Deletes the current selection.

Shape Methods

getShapes(): DraftXShape[]

Returns all shapes in the current document.

getShapeById(id: string): DraftXShape | null

Returns the matching shape or null.

getShapeProperties(): DraftXShapeProperties | null

Returns the current selected shape properties.

Returns null when nothing is selected.

setShapeProperties(patch: DraftXShapePropertyPatch): void

Applies a property patch to the selected shape.

Throws if nothing is selected.

Supported patch fields:

  • x
  • y
  • width
  • height
  • rotation
  • opacity
  • fill
  • stroke
  • strokeWidth
  • text
  • fontSize

History Methods

canUndo(): boolean

Returns whether an undo step is available.

undo(): boolean

Attempts to undo the last change.

Returns:

  • true on success
  • false if nothing can be undone

canRedo(): boolean

Returns whether a redo step is available.

redo(): boolean

Attempts to redo the last undone change.

Returns:

  • true on success
  • false if nothing can be redone

Events

DraftX is event-driven.

Your app calls methods such as setTool, setDocument, moveSelection, or undo. When widget state changes, DraftX emits events that your host app can subscribe to with widget.on(...).

Use that event channel to:

  • keep toolbars and pressed states in sync
  • refresh inspectors and side panels
  • save or serialize the latest document
  • update zoom, grid, and snap readouts
  • respond to shape clicks and selection changes

on(event, listener): () => void

Subscribes to a widget event and returns an unsubscribe function.

const off = widget.on('drawing:changed', (payload) => {
  console.log(payload.reason);
});

off();

Notes:

  • listener receives the event payload for the selected event
  • the returned function removes that one subscription
  • widget.destroy() also releases subscriptions created through widget.on(...)
  • subscribe after widget creation and before users start interacting with the canvas

Event Wiring Patterns

Persist Or Serialize On drawing:changed

const stopDrawingEvents = widget.on('drawing:changed', () => {
  const saved = widget.saveDocument();
  localStorage.setItem('draftx-document', saved);
});

Sync Toolbar State On tool:changed

const stopToolEvents = widget.on('tool:changed', (payload) => {
  syncToolbar(payload.tool);
});

Sync Inspectors On selection:changed

const stopSelectionEvents = widget.on('selection:changed', (payload) => {
  if (payload.primaryId === null) {
    hideInspector();
    return;
  }

  renderInspector(widget.getShapeById(payload.primaryId));
});

Sync View Readouts On view:changed

const stopViewEvents = widget.on('view:changed', (payload) => {
  zoomReadout.textContent = payload.zoom.toFixed(2);
});

Track Canvas Interaction On shape:clicked

const stopShapeClicks = widget.on('shape:clicked', (payload) => {
  if (payload.id !== null) {
    console.log('Clicked shape:', payload.id);
  }
});

Callback Lifecycle

The usual host-side pattern is:

  1. create the widget
  2. register subscriptions
  3. let callbacks keep host UI in sync
  4. unsubscribe and destroy during teardown

Example:

const cleanup: Array<() => void> = [];

cleanup.push(
  widget.on('drawing:changed', () => {
    renderJson(widget.getDocument());
  }),
);

cleanup.push(
  widget.on('selection:changed', (payload) => {
    syncInspector(payload.primaryId, payload.ids);
  }),
);

cleanup.push(
  widget.on('tool:changed', (payload) => {
    syncToolbar(payload.tool);
  }),
);

function stopWidgetScreen(): void {
  for (const stop of cleanup) {
    stop();
  }

  widget.destroy();
}

Supported events:

  • canvas:resized
  • view:changed
  • grid:changed
  • snap:changed
  • theme:changed
  • tool:changed
  • drawing:changed
  • selection:changed
  • shape:clicked

Event Payloads

canvas:resized

interface DraftXCanvasResizedEvent {
  width: number;
  height: number;
  dpr: number;
}

view:changed

interface DraftXViewChangedEvent {
  center: DraftXPoint;
  zoom: number;
}

grid:changed

interface DraftXGridChangedEvent {
  visible: boolean;
}

snap:changed

interface DraftXSnapChangedEvent {
  snapToGrid: boolean;
}

theme:changed

interface DraftXThemeChangedEvent {
  theme: DraftXTheme;
}

tool:changed

interface DraftXToolChangedEvent {
  tool: DraftXTool;
}

drawing:changed

interface DraftXDrawingChangedEvent {
  reason: string;
  shapeId?: string;
}

Typical reason values describe what changed in the drawing, for example loading a document, creating a shape, deleting a selection, or editing shape properties.

selection:changed

interface DraftXSelectionChangedEvent {
  ids: readonly string[];
  primaryId: string | null;
  info?: DraftXSelectionInfo | null;
}

shape:clicked

interface DraftXShapeClickedEvent {
  id: string | null;
}

Document Schema

interface DraftXDocument {
  version: '1.0';
  shapes: DraftXShape[];
}

Shape Types

Base Shape

interface DraftXBaseShape extends DraftXShapeStyle {
  id: string;
  type: DraftXShapeType;
  rotation?: number;
}

Shared Style Fields

interface DraftXShapeStyle {
  fill?: string | null;
  stroke?: string | null;
  strokeWidth?: number;
}

Rectangle

interface DraftXRectShape extends DraftXBaseShape {
  type: 'rect';
  x: number;
  y: number;
  width: number;
  height: number;
}

Ellipse

interface DraftXEllipseShape extends DraftXBaseShape {
  type: 'ellipse';
  x: number;
  y: number;
  width: number;
  height: number;
}

Line

interface DraftXLineShape extends DraftXBaseShape {
  type: 'line';
  x1: number;
  y1: number;
  x2: number;
  y2: number;
}

Text

interface DraftXTextShape extends DraftXBaseShape {
  type: 'text';
  x: number;
  y: number;
  text: string;
  fontSize?: number;
}

Shape Union

type DraftXShape =
  | DraftXRectShape
  | DraftXEllipseShape
  | DraftXLineShape
  | DraftXTextShape;

Notes

  • The widget document format is stable and JSON-based.
  • File import/export belongs in your app code.
  • The widget API is command/query based: create the widget, call methods on widget, and listen for events when needed.

Companion Doc