# 文档格式

> 这个引擎保存的 Fabric.js JSON 格式：格式版本、画布尺寸、带稳定 id 的对象、资源清单和元数据，附 JSON Schema。

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

保存的文档在你熟悉的 Fabric.js JSON 格式外面，加了一层编辑器需要的信息。它是普通 JSON，可以存进任何数据库、通过任何 API 传递，用任何语言读取。

## 结构

```ts
interface FabricDocument {
  schemaVersion: number;
  id: string;
  createdAt: string;
  updatedAt: string;
  revision?: number;
  fabricVersion?: string;
  canvas: { width: number; height: number; background?: unknown };
  objects: SerializedFabricObject[];
  assets?: {
    images: Array<{ url: string; objectIds: string[] }>;
    fonts: Array<{
      family: string;
      weight: string;
      style: string;
      objectIds: string[];
    }>;
  };
  metadata: Record<string, unknown>;
}
```

## 字段

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `schemaVersion` (required) | `number` | — | The format version. `1` for every 1.x release. |
| `id` (required) | `string` | — | The document id. |
| `createdAt` (required) | `string` | — | When the document was created, as an ISO date. |
| `updatedAt` (required) | `string` | — | When it last changed, as an ISO date. |
| `revision` | `number` | — | The saved revision, used to detect conflicts. |
| `fabricVersion` | `string` | — | The Fabric.js version that wrote it. |
| `canvas` (required) | `DocumentCanvas` | — | `{ width, height, background? }`. |
| `objects` (required) | `SerializedFabricObject[]` | — | The serialized objects, in stacking order, each with an id. |
| `assets` | `AssetManifest` | — | The images and fonts the document needs, with the ids of the objects that use them. |
| `metadata` (required) | `Record<string, unknown>` | — | Your own project data, such as title, owner and tags. |

## 对象和 id

`objects` 按叠放顺序存放对象，格式就是 `toObject()` 生成的 Fabric.js JSON 格式，只是每个对象多了一个 `id`。编组里的子对象也有对象 id。id 在对象第一次出现时生成，之后永远不变。

## 元数据

整份文档的数据放在 `metadata`（元数据）里，比如标题、所有者或标签：

```ts
engine.updateMetadata({ title: "Ground floor", tags: ["draft"] });
engine.getDocumentInfo().metadata;
```

`updateMetadata` 会合并改动，并把文档标记为未保存。

## JSON Schema

这个格式由一份随包发布的 JSON Schema 描述。可以用它在其他服务里校验文档，或者为其他语言生成类型：

```ts
import schema from "fabricjs-document-engine/schema/document-v1.json";
```

在 TypeScript 或 JavaScript 里，`validateDocument(value)` 会返回问题列表，并给出每个问题的路径。

## 稳定性

格式版本 1 在所有 1.x 版本中都已冻结。读取方必须忽略不认识的字段，因为次版本可能会加入可选字段。`objects` 里的 Fabric.js JSON 格式跟随你的 Fabric.js 版本，Fabric.js 5、6、7 之间的差异由[迁移](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/migration)步骤处理。
