EditorEngine API Reference

Complete API reference for the EditorEngine class — the central entry point for all editor operations.

Constructor

Creating an Enginetypescript
import { EditorEngine } from '@design-on-web/core';

const canvasEl = document.createElement('canvas');
const engine = new EditorEngine({
  canvasElement: canvasEl,
  width: 1080,
  height: 1080,
  backgroundColor: '#ffffff',
});

EditorEngineConfig

NameTypeDefaultDescription
canvasElement*HTMLCanvasElementCanvas element for Fabric.js. Must be created programmatically with document.createElement('canvas').
widthnumber1080Initial canvas width in pixels.
heightnumber1080Initial canvas height in pixels.
backgroundColorstring'#ffffff'Initial canvas background color.

Shape Operations

Adding Objectstypescript
// Add a rectangle
const rectId = engine.addShape('rect', {
  left: 100, top: 100,
  width: 200, height: 150,
  fill: '#4f46e5',
  stroke: '#312e81',
  strokeWidth: 2,
  rx: 8, ry: 8, // rounded corners
});

// Add a circle
const circleId = engine.addShape('circle', {
  left: 300, top: 200,
  radius: 75,
  fill: '#ef4444',
});

// Add text
const textId = engine.addText('Hello World', {
  left: 100, top: 400,
  fontSize: 48,
  fill: '#1f2937',
  fontFamily: 'Inter',
  fontWeight: 'bold',
});

// Add image (async — waits for image to load)
const imageId = await engine.addImage('https://example.com/photo.jpg', {
  left: 50, top: 50,
  scaleX: 0.5,
  scaleY: 0.5,
});

Methods

NameTypeDefaultDescription
addShape(type, options?)stringAdds a shape ('rect', 'circle', 'triangle', 'line', 'polygon') to the canvas. Returns the object ID.
addText(text, options?)stringAdds a text object to the canvas. Returns the object ID.
addImage(src, options?)Promise<string>Loads an image from URL or data URI and adds it to the canvas. Returns a promise that resolves with the object ID.
removeObject(id)voidRemoves the object with the given ID from the canvas.

Selection

Selectiontypescript
// Get currently selected objects
const selected = engine.getSelectedObjects();
// => [{ id: 'abc123', type: 'rect', left: 100, top: 100, ... }]

// Select a specific object by ID
engine.selectObject('abc123');

// Deselect everything
engine.deselectAll();

// Remove an object
engine.removeObject('abc123');

Methods

NameTypeDefaultDescription
getSelectedObjects()EditorObjectInfo[]Returns an array of info objects for all currently selected objects.
selectObject(id)voidProgrammatically selects the object with the given ID.
deselectAll()voidDeselects all objects on the canvas.

Canvas State

Zoom and Canvas Sizetypescript
// Zoom
const currentZoom = engine.getZoom(); // => 1
engine.setZoom(1.5); // 150%

// Canvas size
const size = engine.getCanvasSize(); // => { width: 1080, height: 1080 }
engine.setCanvasSize({ width: 1920, height: 1080 });

Methods

NameTypeDefaultDescription
getZoom()numberReturns the current zoom level (1 = 100%).
setZoom(level)voidSets the zoom level. Pass 1 for 100%, 2 for 200%, etc.
getCanvasSize(){ width: number; height: number }Returns the current canvas dimensions.
setCanvasSize(size)voidSets the canvas dimensions. Accepts { width: number; height: number }.

Grid Snap

Enable grid snapping so objects snap to a configurable grid when moved or resized.

Grid Snaptypescript
// Enable grid snapping
engine.enableGridSnap(true);

// Set snap increment to 25px (default is 50)
engine.setGridSnapSize(25);

// Disable grid snapping
engine.enableGridSnap(false);

Methods

NameTypeDefaultDescription
enableGridSnap(enable)voidEnables or disables grid snapping. When enabled, objects snap to the nearest grid intersection while being dragged.
setGridSnapSize(size)voidSets the grid snap increment in pixels. Default is 50. Smaller values give finer control; larger values enforce stricter alignment.

Ruler Guides

Add horizontal and vertical ruler guides to the canvas. Guides are visual reference lines that help with alignment. Objects can snap to guides when smart guides are enabled.

Ruler Guidestypescript
// Add a horizontal guide at y=200
const guideId = engine.addGuide('horizontal', 200);

// Add a vertical guide at x=540
const guideId2 = engine.addGuide('vertical', 540);

// List all guides
const guides = engine.getGuides();
// => [{ id: 'guide-1', axis: 'horizontal', position: 200 }, ...]

// Remove a specific guide
engine.removeGuide(guideId);

// Clear all guides
engine.clearGuides();

Methods

NameTypeDefaultDescription
addGuide(axis, position)stringAdds a ruler guide. axis is 'horizontal' or 'vertical'; position is the pixel offset from the top (horizontal) or left (vertical) edge. Returns the guide ID.
removeGuide(id)voidRemoves the ruler guide with the given ID.
clearGuides()voidRemoves all ruler guides from the canvas.
getGuides()Guide[]Returns an array of all current guides. Each Guide has: { id: string, axis: 'horizontal' | 'vertical', position: number }.

History (Undo/Redo)

Undo / Redotypescript
// Undo the last operation
engine.undo();

// Redo the last undone operation
engine.redo();

// Check availability
if (engine.canUndo()) engine.undo();
if (engine.canRedo()) engine.redo();

Methods

NameTypeDefaultDescription
undo()voidReverses the last operation on the command stack.
redo()voidRe-applies the last undone operation.
canUndo()booleanReturns true if there are operations to undo.
canRedo()booleanReturns true if there are operations to redo.

Serialization

Save and Loadtypescript
// Save canvas state to JSON string
const json = engine.toJSON();
localStorage.setItem('myDesign', json);

// Load canvas state from JSON string
const saved = localStorage.getItem('myDesign');
if (saved) {
  await engine.loadJSON(saved);
}

Methods

NameTypeDefaultDescription
toJSON()stringSerializes the entire canvas state (all pages, objects, settings) to a JSON string.
loadJSON(json)Promise<void>Restores canvas state from a previously serialized JSON string.

Export

Exportingtypescript
// Basic export
const pngBlob = await engine.exportAs('png');

// With options
const hiResBlob = await engine.exportAs('png', { multiplier: 2 });
const jpegBlob = await engine.exportAs('jpeg', { quality: 0.85 });
const pdfBlob = await engine.exportAs('pdf');

Methods

NameTypeDefaultDescription
exportAs(format, options?)Promise<Blob>Exports the canvas to the specified format. Returns a Blob. Supported formats: 'png', 'jpeg', 'webp', 'svg', 'pdf', 'psd', 'tiff', 'json'.

See the Export API Reference for format-specific options and plugin registration.

Drawing

Freehand Drawingtypescript
// Enable freehand drawing mode
engine.setDrawingMode(true);

// Configure the brush
engine.updateBrush({
  color: '#ff0000',
  width: 5,
  opacity: 0.8,
});

// Disable drawing mode
engine.setDrawingMode(false);

Methods

NameTypeDefaultDescription
setDrawingMode(enabled)voidEnables or disables freehand drawing mode on the canvas.
updateBrush(config)voidUpdates brush settings. Config: { color?: string, width?: number, opacity?: number }.

Text Effects

Text Effectstypescript
// Apply text shadow
engine.applyTextShadow(textId, {
  color: 'rgba(0,0,0,0.5)',
  blur: 4,
  offsetX: 2,
  offsetY: 2,
});

// Remove text shadow
engine.applyTextShadow(textId, null);

// Apply text outline (stroke)
engine.applyTextOutline(textId, {
  color: '#000000',
  width: 2,
});

// Remove text outline
engine.applyTextOutline(textId, null);

// Apply text decoration
engine.applyTextDecoration(textId, {
  underline: true,
  linethrough: false,
});

Methods

NameTypeDefaultDescription
applyTextShadow(id, config | null)voidApplies or removes a shadow on a text object. Config: { color, blur, offsetX, offsetY }. Pass null to remove.
applyTextOutline(id, config | null)voidApplies or removes a stroke outline on a text object. Config: { color, width }. Pass null to remove.
applyTextDecoration(id, config)voidSets text decoration. Config: { underline?: boolean, linethrough?: boolean }.

Gradient

Gradient Filltypescript
// Apply gradient fill
engine.applyGradientFill(rectId, {
  type: 'linear', // 'linear' | 'radial'
  angle: 90,
  colorStops: [
    { offset: 0, color: '#4f46e5' },
    { offset: 1, color: '#7c3aed' },
  ],
});

Methods

NameTypeDefaultDescription
applyGradientFill(id, config)voidApplies a gradient fill to an object. Config: { type: 'linear' | 'radial', angle?: number, colorStops: Array<{ offset: number, color: string }> }.

Image Effects

Filter presets, individual image filters, overlay textures, and blend modes for image manipulation.

Filter Methods

NameTypeDefaultDescription
applyImageFilter(id, filterName, value)voidApplies or removes a single filter on an image. Filters: brightness (-1..1), contrast (-1..1), saturation (-1..1), blur (0..1), grayscale (0|1), sepia (0|1). Setting neutral value (0) removes the filter.
applyFilterPreset(id, presetName)voidApplies a named filter preset. Presets: none, xpro, lomo, sepia-warm, bw, vintage, cool, dramatic, soft, vivid. 'none' resets all filters.
getFilterPresets()Array<{ name, filters }>Returns the list of available filter presets with their filter values.

Overlay Texture Methods

NameTypeDefaultDescription
addOverlayTexture(imageId, src, options?)Promise<string | null>Adds a texture overlay on top of an image. Options: { blendMode?: string (default 'overlay'), opacity?: number (default 0.5) }. Returns overlay ID. Replaces existing overlay if one exists.
removeOverlayTexture(imageId)voidRemoves the overlay texture from the specified image.
setOverlayBlendMode(imageId, mode)voidChanges the overlay blend mode.
setOverlayOpacity(imageId, opacity)voidSets overlay opacity (0 to 1).
getOverlayForImage(imageId)object | nullReturns { id, blendMode, opacity } for the image's overlay, or null.

Blend Mode Methods

NameTypeDefaultDescription
setBlendMode(id, mode)voidSets the blend mode on any object. Modes: source-over (normal), multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion.

Properties

Updating Propertiestypescript
// Update any object property
engine.applyProperties(rectId, {
  fill: '#10b981',
  opacity: 0.8,
  angle: 45,
  scaleX: 1.5,
  scaleY: 1.5,
});

Methods

NameTypeDefaultDescription
applyProperties(id, properties)voidUpdates arbitrary properties on an object. Accepts any valid Fabric.js object properties: fill, opacity, angle, scaleX, scaleY, left, top, etc.

Copy/Paste Style

Copy visual styles from one object and apply them to others. Useful for quickly unifying the appearance of multiple objects.

Copy and Paste Styletypescript
// Copy style from one object
const style = engine.copyStyle('rect-abc');
// => { fill: '#4f46e5', stroke: '#312e81', strokeWidth: 2, opacity: 1, ... }

// Paste style onto one or more target objects
if (style) {
  engine.pasteStyle(['circle-xyz', 'triangle-123'], style);
}

Methods

NameTypeDefaultDescription
copyStyle(id)ObjectStyle | nullCopies the visual style of the object with the given ID. Returns null if the object is not found. ObjectStyle includes: fill, stroke, strokeWidth, strokeDashArray, opacity, shadow, fontFamily, fontSize, fontWeight, fontStyle, textAlign, lineHeight, charSpacing, underline, linethrough, overline, paintFirst, strokeLineCap, strokeLineJoin, globalCompositeOperation.
pasteStyle(targetIds, style)voidApplies a previously copied ObjectStyle to one or more target objects. Only style properties present in the ObjectStyle object are applied; other properties remain unchanged.

Z-Order (Layering)

Z-Ordertypescript
// Move forward/backward in the layer stack
engine.bringForward(rectId);
engine.sendBackward(rectId);
engine.bringToFront(rectId);
engine.sendToBack(rectId);

Methods

NameTypeDefaultDescription
bringForward(id)voidMoves the object one layer up in the stack.
sendBackward(id)voidMoves the object one layer down in the stack.
bringToFront(id)voidMoves the object to the top of the layer stack.
sendToBack(id)voidMoves the object to the bottom of the layer stack.

Product Configuration

Configure the editor for a specific printing product. A product config defines the mockup image, print area position and size, and canvas dimensions in centimeters. This is the foundation of the printing workflow.

Product Configurationtypescript
// Define a product configuration (e.g., for a t-shirt)
const tshirtConfig: ProductConfig = {
  id: 'tshirt-white-front',
  name: 'White T-Shirt — Front',
  mockupImage: '/assets/mockups/tshirt-white.png',
  printArea: { x: 280, y: 180, width: 520, height: 620 },
  canvasSizeCm: { width: 30, height: 40 },
  dielineImage: '/assets/dielines/tshirt-front.svg',
};

// Apply product config with a specific print size
await engine.applyProductConfig(tshirtConfig, {
  label: 'A4',
  widthCm: 21,
  heightCm: 29.7,
});

// Change print size later (recalculates canvas)
engine.changePrintSize({ label: 'A3', widthCm: 29.7, heightCm: 42 });

// Get current product config
const active = engine.getActiveProductConfig();

// Clear product configuration
engine.clearProductConfig();

Methods

NameTypeDefaultDescription
applyProductConfig(config, printSize?)Promise<void>Applies a product configuration. Sets up the mockup, dieline, print area, and canvas size. Optionally accepts a print size to calculate initial canvas dimensions.
changePrintSize(printSize)voidChanges the active print size. Recalculates the canvas dimensions based on the product config's canvasSizeCm and the new print size ratios.
getActiveProductConfig()ProductConfig | nullReturns the currently active product configuration, or null if none is set.
clearProductConfig()voidClears the active product configuration, removing the mockup and dieline.

ProductConfig Interface

NameTypeDefaultDescription
id*stringUnique identifier for the product.
name*stringDisplay name of the product.
mockupImage*stringURL or path to the mockup image.
printArea*{ x, y, width, height }Position and size of the print area on the mockup, in pixels.
canvasSizeCm*{ width, height }Physical canvas dimensions in centimeters.
dielineImagestringOptional URL or path to a dieline SVG/image overlay.

PrintSizeOption Interface

NameTypeDefaultDescription
label*stringDisplay label (e.g., 'A4', 'A3', 'Custom').
widthCm*numberWidth in centimeters.
heightCm*numberHeight in centimeters.

Background Mockup & Dieline

Low-level methods for managing the background mockup and dieline overlay independently of the product configuration system. These are useful when you need direct control over the visual guide layers.

Mockup & Dieline Methodstypescript
// Background mockup — image behind the canvas
await engine.setBackgroundMockup('/assets/tshirt-mockup.png', {
  opacity: 0.9,
});
engine.updateBackgroundMockup({ opacity: 0.5 });
engine.removeBackgroundMockup();

// Dieline overlay — SVG/image on top of the canvas
await engine.setDielineOverlay('/assets/box-dieline.svg', {
  opacity: 0.6,
});
engine.updateDielineOverlay({ opacity: 0.3 });
engine.toggleDielineVisibility(false); // hide
engine.toggleDielineVisibility();      // toggle
engine.removeDielineOverlay();

// Access the underlying manager
const manager = engine.getMockupDielineManager();

Background Mockup Methods

NameTypeDefaultDescription
setBackgroundMockup(src, options?)Promise<void>Loads an image and places it behind the canvas as a non-exportable, non-selectable background. Options: { opacity?: number }.
removeBackgroundMockup()voidRemoves the background mockup from the canvas.
updateBackgroundMockup(options)voidUpdates the mockup properties without reloading the image. Options: { opacity?: number }.

Dieline Overlay Methods

NameTypeDefaultDescription
setDielineOverlay(src, options?)Promise<void>Loads an SVG or image and places it on top of the canvas as a non-exportable, non-selectable overlay. Options: { opacity?: number }.
removeDielineOverlay()voidRemoves the dieline overlay from the canvas.
updateDielineOverlay(options)voidUpdates the dieline overlay properties without reloading. Options: { opacity?: number }.
toggleDielineVisibility(visible?)voidToggles dieline visibility. Pass true/false to set explicitly, or omit to toggle current state.
getMockupDielineManager()MockupDielineManagerReturns the underlying MockupDielineManager instance for advanced control.
💡
Use product config for full setup
For most use cases, prefer applyProductConfig() which sets up both the mockup and dieline in one call. Use these low-level methods only when you need independent control over each layer.

Accessors

Internal Accessorstypescript
// Canvas instance (Fabric.js Canvas)
const canvas = engine.getCanvas();

// EventBus for pub/sub events
const eventBus = engine.getEventBus();

// Zustand store for state management
const store = engine.getStore();

// Plugin registry
const plugins = engine.getPluginRegistry();

// Manager instances
const exportManager = engine.getExportManager();
const canvasManager = engine.getCanvasManager();
const templateManager = engine.getTemplateManager();
const pageManager = engine.getPageManager();
const versionManager = engine.getVersionManager();

Methods

NameTypeDefaultDescription
getCanvas()fabric.CanvasReturns the underlying Fabric.js Canvas instance.
getEventBus()EventBusReturns the EventBus for subscribing to editor events.
getStore()StoreApiReturns the Zustand store for reading/subscribing to state.
getPluginRegistry()PluginRegistryReturns the plugin registry for inspecting loaded plugins.
getExportManager()ExportManagerReturns the export manager for programmatic export control.
getCanvasManager()CanvasManagerReturns the canvas manager for low-level canvas operations.
getTemplateManager()TemplateManagerReturns the template manager for loading/saving templates.
getPageManager()PageManagerReturns the page manager for multi-page operations.
getVersionManager()VersionManagerReturns the version manager for version history operations.
⚠️
Internal APIs
The accessor methods expose internal managers. Their APIs may change between minor versions. For most use cases, prefer the top-level EditorEngine methods instead.

Lifecycle

Register Plugintypescript
import { PsdExportPlugin } from '@design-on-web/export-psd';

await engine.registerPlugin(PsdExportPlugin);
Destroytypescript
// Release all resources
engine.destroy();

Methods

NameTypeDefaultDescription
registerPlugin(plugin)Promise<void>Registers an editor plugin (e.g., export format). Returns a promise that resolves when the plugin is initialized.
destroy()voidDisposes the engine and releases all resources. Call this when removing the editor from the page.