# DocumentEngine

> 所有 DocumentEngine 方法：保存和加载文档、撤销和重做、导出、版本、恢复、资源和事件，附类型和行为说明。

Source: https://fabricjs-document-engine.jscrate.dev/zh/docs/api/document-engine
Last updated: 2026-09-28

`createDocumentEngine` 返回一个 `DocumentEngine`。下表列出所有 DocumentEngine 方法和属性。会访问存储或画布的方法都返回 promise。

## 成员

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `canvas` (required) | `StaticCanvas` | — | The canvas you passed in. |
| `getDocumentInfo` (required) | `(): DocumentInfo` | — | `{ id, createdAt, updatedAt, metadata }` of the current document. |
| `updateMetadata` (required) | `(changes: Record<string, unknown>): void` | — | Merges `changes` into the metadata and marks the document as unsaved. |
| `newDocument` (required) | `(options?: NewDocumentRequest): void` | — | Clears the canvas and starts a new document. |
| `toDocument` (required) | `(): FabricDocument` | — | Serializes the canvas into a `FabricDocument`. Every object gets an id. |
| `loadDocument` (required) | `(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` (required) | `(documentId: string, options?: LoadOptions): Promise<FabricDocument>` | — | Loads a document from `storage`. It keeps `documentId` even if it was stored as plain Fabric JSON. |
| `importFabricJson` (required) | `(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` (required) | `(name?: string): Promise<VersionSummary>` | — | Keeps a named version of the current document. |
| `listVersions` (required) | `(documentId?: string): Promise<VersionSummary[]>` | — | Version summaries, newest first. |
| `restoreVersion` (required) | `(versionId: string): Promise<FabricDocument>` | — | Keeps an automatic `Before restoring "..."` version first, then loads the old content as a new, unsaved revision. |
| `deleteVersion` (required) | `(versionId: string): Promise<void>` | — | Deletes a version. |
| `save` (required) | `(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` (required) | `(): boolean` | — | Whether there are unsaved changes. |
| `getSaveState` (required) | `(): SaveState` | — | The current `SaveState`. |
| `registerObject` (required) | `(definition: CustomObjectDefinition): void` | — | Registers a custom class after the engine was created. |
| `transaction` (required) | `<Result>(label: string, work: () => Result): Result` | — | Records everything `work` changes as one labelled undo step. Nested and async work is supported. |
| `commit` (required) | `(label?: string): boolean` | — | Records changes your code made since the last step. Returns `false` if nothing changed. |
| `undo` (required) | `(): Promise<boolean>` | — | Undoes one step. Calls run in order. A failure rejects with `HISTORY_FAILED` and keeps the step. |
| `redo` (required) | `(): Promise<boolean>` | — | Redoes one step. Calls run in order. |
| `canUndo` (required) | `(): boolean` | — | Whether there is a step to undo. |
| `canRedo` (required) | `(): boolean` | — | Whether there is a step to redo. |
| `getHistory` (required) | `(): { undo: string[]; redo: string[]; }` | — | The labels of the undo and redo steps, newest first. |
| `clearHistory` (required) | `(): void` | — | Forgets every undo and redo step. |
| `getObjectById` (required) | `(id: string): FabricObject \| undefined` | — | Finds any object by its id, including objects inside groups. |
| `getAssetManifest` (required) | `(): AssetManifest` | — | The images and fonts the current canvas uses. |
| `checkAssets` (required) | `(): Promise<AssetReport>` | — | Loads every image and font and reports `{ manifest, missingImages, unavailableFonts, warnings }`. |
| `replaceImage` (required) | `(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` (required) | `(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` (required) | `(options: ExportOptions): Promise<ExportPreflight>` | — | Runs the export checks without exporting: `{ ok, problems, warnings }`. |
| `flushRecovery` (required) | `(): Promise<void>` | — | Writes a recovery copy right now. |
| `getRecoverableDocuments` (required) | `(): Promise<RecoveryRecord[]>` | — | Every recovery copy, newest first. |
| `getRecovery` (required) | `(documentId?: string): Promise<RecoveryRecord \| undefined>` | — | One recovery copy. The default is the current document. |
| `restoreRecovery` (required) | `(documentId?: string, options?: LoadOptions): Promise<FabricDocument>` | — | Loads a recovery copy as unsaved work, keeping the revision it was based on. |
| `discardRecovery` (required) | `(documentId?: string): Promise<void>` | — | Deletes a recovery copy. |
| `getInterruptedLoad` (required) | `(): Promise<InterruptedLoad \| undefined>` | — | `{ documentId, startedAt }` of a load that never finished, for example because the tab crashed. |
| `on` (required) | `<Name extends keyof DocumentEngineEvents>(name: Name, handler: (payload: DocumentEngineEvents[Name]) => void): Unsubscribe` | — | Subscribes to an event. Returns a function that unsubscribes. |
| `destroy` (required) | `(): void` | — | Stops listening and cancels loads, saves and timers. Writes a recovery copy if there is unsaved work. Later calls throw `ENGINE_DESTROYED`. |

## 方法的参数

### 加载配置

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `restoreCanvasSize` | `boolean` | — | Resize the canvas to the size stored in the document. |
| `discardUnsavedChanges` | `boolean` | `false` | Open the document even though the current one has unsaved changes. Without it, the call refuses with `UNSAVED_CHANGES`. |

### 导入配置

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | `a new id` | The id of the new document. |
| `metadata` | `Record<string, unknown>` | `{}` | Metadata for the new document. |
| `restoreCanvasSize` | `boolean` | — | Resize the canvas to the size stored in the document. Inherited from LoadOptions. |
| `discardUnsavedChanges` | `boolean` | `false` | Open the document even though the current one has unsaved changes. Without it, the call refuses with `UNSAVED_CHANGES`. Inherited from LoadOptions. |

### 保存配置

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `overwrite` | `boolean` | `false` | Skip the revision check and keep this version after a `SAVE_CONFLICT`. |

### 保存状态

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `status` (required) | `SaveStatus` | — | One of `saved`, `unsaved`, `saving`, `error` or `conflict`. |
| `isDirty` (required) | `boolean` | — | Whether there are unsaved changes. |
| `isSaving` (required) | `boolean` | — | Whether a save is running. |
| `revision` (required) | `number` | — | The revision last saved or loaded. |
| `lastSavedAt` (required) | `string \| undefined` | — | When the last save finished, as an ISO date. |
| `error` (required) | `DocumentEngineError \| undefined` | — | The error of the last failed save. |

### 导出配置

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `format` (required) | `ExportFormat` | — | `'png'`, `'jpeg'`, `'webp'`, `'svg'` or `'json'`. |
| `scale` | `number` | `1` | Output size multiplier, such as `2` for retina screens. |
| `quality` | `number` | `0.92` | 0 to 1, for JPEG and WebP. |
| `area` | `ExportArea` | `'canvas'` | `'canvas'`, `'content'` (every object), `'selection'`, or `{ left, top, width, height }`. |
| `padding` | `number` | `0` | Extra space around `content` or `selection`. |
| `background` | `ExportBackground` | `'keep'` | `'keep'`, `'transparent'` or any CSS color. |
| `signal` | `AbortSignal` | — | An `AbortSignal` that cancels the export. |

### 导出结果

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `format` (required) | `ExportFormat` | — | The format you asked for. |
| `mimeType` (required) | `string` | — | The MIME type of `blob`. |
| `blob` (required) | `Blob` | — | The file, ready to download or upload. |
| `width` (required) | `number` | — | Output width in pixels. |
| `height` (required) | `number` | — | Output height in pixels. |
| `warnings` (required) | `AssetWarning[]` | — | Asset warnings, such as a font that fell back. |
| `document` | `FabricDocument` | — | JSON exports only: the portable document. |

## 适用于所有 DocumentEngine 方法的规则

- 加载失败永远不会清空画布或只加载一半。
- 接入存储适配器后，只要有未保存的改动，`load`、`loadDocument`、`importFabricJson` 和 `newDocument` 都会以 `UNSAVED_CHANGES` 拒绝，除非传入 `discardUnsavedChanges: true`。
- 同一时间只有一次保存。保存期间再调用 `save`，会合并为一次后续保存。
- `undo` 和 `redo` 调用按顺序执行。
- `export` 不会改变画布、历史记录或未保存状态。
- 调用 `destroy()` 之后，任何调用都会抛出 `ENGINE_DESTROYED`。

每组 DocumentEngine 方法的详细说明见指南：[保存和加载](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/save-and-load)、[撤销和重做](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/undo-redo)和[导出](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/export)。
