Fabric.js Document Engine

Search documentation

Find a page or section

中文

DocumentEngine

View as Markdown

The object createDocumentEngine returns.

createDocumentEngine returns a DocumentEngine. The table below lists all DocumentEngine methods and properties. Methods that touch storage or the canvas return a promise.

Members

NameTypeDefaultDescription
canvas*StaticCanvas—The canvas you passed in.
getDocumentInfo*(): DocumentInfo—{ id, createdAt, updatedAt, metadata } of the current document.
updateMetadata*(changes: Record<string, unknown>): void—Merges changes into the metadata and marks the document as unsaved.
newDocument*(options?: NewDocumentRequest): void—Clears the canvas and starts a new document.
toDocument*(): FabricDocument—Serializes the canvas into a FabricDocument. Every object gets an id.
loadDocument*(document: unknown, options?: LoadOptions): Promise<FabricDocument>—Validates, migrates and checks the assets of a document, then loads it. A failed load leaves the canvas untouched.
load*(documentId: string, options?: LoadOptions): Promise<FabricDocument>—Loads a document from storage. It keeps documentId even if it was stored as plain Fabric JSON.
importFabricJson*(json: string | Record<string, unknown>, options?: ImportOptions): Promise<FabricDocument>—Opens plain Fabric JSON, such as canvas.toJSON() output, as text or as an object.
createVersion*(name?: string): Promise<VersionSummary>—Keeps a named version of the current document.
listVersions*(documentId?: string): Promise<VersionSummary[]>—Version summaries, newest first.
restoreVersion*(versionId: string): Promise<FabricDocument>—Keeps an automatic Before restoring "..." version first, then loads the old content as a new, unsaved revision.
deleteVersion*(versionId: string): Promise<void>—Deletes a version.
save*(options?: SaveOptions): Promise<FabricDocument>—Saves through storage. Only one save runs at a time, and calls made during a save merge into one follow-up.
isDirty*(): boolean—Whether there are unsaved changes.
getSaveState*(): SaveState—The current SaveState.
registerObject*(definition: CustomObjectDefinition): void—Registers a custom class after the engine was created.
transaction*<Result>(label: string, work: () => Result): Result—Records everything work changes as one labelled undo step. Nested and async work is supported.
commit*(label?: string): boolean—Records changes your code made since the last step. Returns false if nothing changed.
undo*(): Promise<boolean>—Undoes one step. Calls run in order. A failure rejects with HISTORY_FAILED and keeps the step.
redo*(): Promise<boolean>—Redoes one step. Calls run in order.
canUndo*(): boolean—Whether there is a step to undo.
canRedo*(): boolean—Whether there is a step to redo.
getHistory*(): { undo: string[]; redo: string[]; }—The labels of the undo and redo steps, newest first.
clearHistory*(): void—Forgets every undo and redo step.
getObjectById*(id: string): FabricObject | undefined—Finds any object by its id, including objects inside groups.
getAssetManifest*(): AssetManifest—The images and fonts the current canvas uses.
checkAssets*(): Promise<AssetReport>—Loads every image and font and reports { manifest, missingImages, unavailableFonts, warnings }.
replaceImage*(oldUrl: string, newUrl: string): Promise<number>—Replaces every image that uses oldUrl, keeping each one's size on the page, as one undo step. Returns how many were replaced.
export*(options: ExportOptions): Promise<ExportResult>—Exports PNG, JPEG, WebP, SVG or JSON. Rejects with EXPORT_BLOCKED and a list of problems when something would break the output.
preflightExport*(options: ExportOptions): Promise<ExportPreflight>—Runs the export checks without exporting: { ok, problems, warnings }.
flushRecovery*(): Promise<void>—Writes a recovery copy right now.
getRecoverableDocuments*(): Promise<RecoveryRecord[]>—Every recovery copy, newest first.
getRecovery*(documentId?: string): Promise<RecoveryRecord | undefined>—One recovery copy. The default is the current document.
restoreRecovery*(documentId?: string, options?: LoadOptions): Promise<FabricDocument>—Loads a recovery copy as unsaved work, keeping the revision it was based on.
discardRecovery*(documentId?: string): Promise<void>—Deletes a recovery copy.
getInterruptedLoad*(): Promise<InterruptedLoad | undefined>—{ documentId, startedAt } of a load that never finished, for example because the tab crashed.
on*<Name extends keyof DocumentEngineEvents>(name: Name, handler: (payload: DocumentEngineEvents[Name]) => void): Unsubscribe—Subscribes to an event. Returns a function that unsubscribes.
destroy*(): void—Stops listening and cancels loads, saves and timers. Writes a recovery copy if there is unsaved work. Later calls throw ENGINE_DESTROYED.

Method options

Load options

NameTypeDefaultDescription
restoreCanvasSizeboolean—Resize the canvas to the size stored in the document.
discardUnsavedChangesbooleanfalseOpen the document even though the current one has unsaved changes. Without it, the call refuses with UNSAVED_CHANGES.

Import options

NameTypeDefaultDescription
idstringa new idThe id of the new document.
metadataRecord<string, unknown>{}Metadata for the new document.
restoreCanvasSizeboolean—Resize the canvas to the size stored in the document.Inherited from LoadOptions.
discardUnsavedChangesbooleanfalseOpen the document even though the current one has unsaved changes. Without it, the call refuses with UNSAVED_CHANGES.Inherited from LoadOptions.

Save options

NameTypeDefaultDescription
overwritebooleanfalseSkip the revision check and keep this version after a SAVE_CONFLICT.

Save state

NameTypeDefaultDescription
status*SaveStatus—One of saved, unsaved, saving, error or conflict.
isDirty*boolean—Whether there are unsaved changes.
isSaving*boolean—Whether a save is running.
revision*number—The revision last saved or loaded.
lastSavedAt*string | undefined—When the last save finished, as an ISO date.
error*DocumentEngineError | undefined—The error of the last failed save.

Export options

NameTypeDefaultDescription
format*ExportFormat—'png', 'jpeg', 'webp', 'svg' or 'json'.
scalenumber1Output size multiplier, such as 2 for retina screens.
qualitynumber0.920 to 1, for JPEG and WebP.
areaExportArea'canvas''canvas', 'content' (every object), 'selection', or { left, top, width, height }.
paddingnumber0Extra space around content or selection.
backgroundExportBackground'keep''keep', 'transparent' or any CSS color.
signalAbortSignal—An AbortSignal that cancels the export.

Export result

NameTypeDefaultDescription
format*ExportFormat—The format you asked for.
mimeType*string—The MIME type of blob.
blob*Blob—The file, ready to download or upload.
width*number—Output width in pixels.
height*number—Output height in pixels.
warnings*AssetWarning[]—Asset warnings, such as a font that fell back.
documentFabricDocument—JSON exports only: the portable document.

Rules that apply to all DocumentEngine methods

  • A failed load never clears or half-fills the canvas.
  • With a storage adapter, load, loadDocument, importFabricJson and newDocument refuse with UNSAVED_CHANGES while there are unsaved changes, unless you pass discardUnsavedChanges: true.
  • Only one save runs at a time. save calls made during a save merge into one follow-up.
  • undo and redo calls run in order.
  • export never changes the canvas, the history or the unsaved state.
  • After destroy(), every call throws ENGINE_DESTROYED.

The guides explain each group in depth: save and load, undo and redo and export.

DocumentEngine methods | Fabric.js Document Engine