Fabric.js Document Engine

搜索文档

查找页面或章节

EN

辅助函数

查看 Markdown

主入口里的几个小函数,浏览器和 Node 都能用。

主入口在 createDocumentEngine 之外还导出了几个文档引擎辅助函数。浏览器相关的函数把引擎接入页面,文档相关的函数在 Node 里无需画布也能运行。

浏览器辅助函数

function bindKeyboardShortcuts(engine: UndoRedoTarget, options?: KeyboardShortcutOptions): () => void

Ctrl/Cmd+Z undoes. Ctrl/Cmd+Shift+Z and Ctrl+Y redo. Ignored while the user types in an input or in Fabric text. Returns an unbind function.

function bindUnsavedChangesWarning(engine: UnsavedChangesSource, target?: EventTarget): () => void

Asks the browser to confirm before a page with unsaved changes closes. Returns an unbind function.

function downloadExport(result: DownloadableExport, fileName?: string): void

Starts a browser download of an export result.

NameTypeDefaultDescription
targetEventTargetwindowWhere to listen for key presses.

剪贴板和图层

function createClipboard(engine: DocumentEngine, options?: ClipboardOptions): Clipboard

A clipboard for one engine. Copies keep custom properties and the real position of objects in groups and selections. Each paste gets fresh ids and is one undo step.

NameTypeDefaultDescription
copy*(objects?: readonly FabricObject[]): number—Copies objects, or the selection. Returns how many were copied.
cut*(objects?: readonly FabricObject[]): number—Copies, then removes the objects as one undo step. The next paste lands in place.
paste*(options?: PasteOptions): Promise<FabricObject[]>—Adds a copy with fresh ids as one undo step, and selects it. Returns the new objects.
hasContent*(): boolean—Whether something was copied.
read*(): ClipboardContent | undefined—The copied objects as plain JSON, for the system clipboard.
write*(content: unknown): void—Replaces the content, for example with JSON from another tab. It is checked like a loaded document.
clear*(): void—Empties the clipboard.
NameTypeDefaultDescription
offsetnumber10How far each paste moves from the last one.
limitsContentLimitsnoneLimits for content passed to write, as for loading documents.
NameTypeDefaultDescription
targetDocumentEnginethe clipboard's engineThe engine to paste into.
offsetnumberthe clipboard's offsetOverrides the offset for this paste.
selectbooleantrueSelects the pasted objects on an interactive canvas.
function bringToFront(engine: DocumentEngine, objects?: readonly FabricObject[], options?: LayerOptions): boolean

Moves objects, or the selection, to the top of the stack as one undo step. Returns false when nothing moved.

function sendToBack(engine: DocumentEngine, objects?: readonly FabricObject[], options?: LayerOptions): boolean

Moves objects, or the selection, to the bottom of the stack as one undo step.

function bringForward(engine: DocumentEngine, objects?: readonly FabricObject[], options?: LayerOptions): boolean

Moves objects one step up. Selected neighbours move as a block.

function sendBackward(engine: DocumentEngine, objects?: readonly FabricObject[], options?: LayerOptions): boolean

Moves objects one step down. Selected neighbours move as a block.

function moveToIndex(engine: DocumentEngine, objects: readonly FabricObject[], index: number, options?: LayerOptions): boolean

Moves objects to an index counted from the bottom, as a block.

function getLayers(engine: DocumentEngine): LayerInfo[]

The top-level objects from top to bottom, for a layers panel.

NameTypeDefaultDescription
pinnedLayerPinnoneObjects this returns true for never move and keep their place, such as a background or a frame.

它们怎样配合使用,见复制、粘贴和图层。

批量渲染

function renderDocuments(documents: Iterable<unknown> | AsyncIterable<unknown>, options: RenderDocumentsOptions): AsyncGenerator<RenderedDocument, void, undefined>

Renders many documents on a few reused off-screen canvases and yields each result as it finishes. Every canvas it creates is freed.

NameTypeDefaultDescription
concurrencynumber2How many documents render at the same time.
signalAbortSignalnoneStops the batch with EXPORT_ABORTED.
onProgress(progress: { done: number; total: number | undefined; }) => voidnoneCalled with { done, total } after each document.
customObjectsCustomObjectDefinition[][]Custom classes, as for createDocumentEngine.
assetsAssetOptions{}Asset options, as for createDocumentEngine.
limitsContentLimitsdefaultsSafety limits, as for createDocumentEngine.
NameTypeDefaultDescription
index*number—Position of the document in the input.
documentId*string | undefined—The document's id, when it has one.
resultExportResult—The export result, when it rendered.
errorDocumentEngineError—Why it failed. The other documents still render.

详见批量渲染。

适用于任何框架的状态

function createDocumentStateStore(engine: DocumentEngine): DocumentStateStore

Framework-free { getSnapshot, subscribe, destroy } with DocumentState. Fits Vue, Svelte and useSyncExternalStore.

文档辅助函数

这些文档引擎辅助函数在任何地方都能运行,包括服务器:

function validateDocument(value: unknown): DocumentIssue[]

Checks a value against the document format. Returns a list of issues with the path of each problem.

function migrateDocument(value: unknown, context: MigrationContext, steps?: Readonly<Record<number, Migration>>, targetVersion?: number): MigrationResult

Upgrades an older document or plain Fabric JSON to the current format. Useful for server-side batch upgrades.

function detectSchemaVersion(value: unknown): number | undefined

Returns 1 for a document, 0 for plain Fabric JSON, otherwise undefined.

function secureDocument(input: unknown, limits?: ContentLimits): unknown

Removes prototype keys and enforces the object and depth limits. Throws UNSAFE_DOCUMENT.

function isSafeImageUrl(url: string): boolean

The default image address rule: http, https, blob, relative addresses and data:image/ are allowed.

错误

function isDocumentEngineError(value: unknown): value is DocumentEngineError

Type guard for DocumentEngineError, which carries a stable code.

示例:在服务器上检查上传

import {
  migrateDocument,
  secureDocument,
  validateDocument,
} from "fabricjs-document-engine";
 
const safe = secureDocument(body, { maxObjects: 20000 });
const { document } = migrateDocument(safe, {
  canvasWidth: 1200,
  canvasHeight: 800,
});
const issues = validateDocument(document);

关于这些文档引擎辅助函数的更多内容,见安全和迁移。

文档引擎辅助函数 | Fabric.js Document Engine