在 Fabric.js React 项目里,关键在时机:画布要在第一次渲染之后才存在,引擎要在卸载时销毁。fabricjs-document-engine/react 入口用几个 hooks 把这两件事都处理好了。
正在加载在线示例,代码在下方。
"use client";
import { bindKeyboardShortcuts } from "fabricjs-document-engine";
import {
useDocumentEngine,
useDocumentState,
} from "fabricjs-document-engine/react";
import {
CircleIcon,
PaletteIcon,
Redo2Icon,
SquareIcon,
Undo2Icon,
} from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useRef } from "react";
import {
COLORS,
DemoCanvas,
DemoFrame,
newShape,
seedShapes,
Status,
Toolbar,
ToolButton,
} from "./demo-ui";
import { useFabricCanvas } from "./use-fabric-canvas";
export default function UndoRedoDemo() {
const t = useTranslations("demos");
const { elementRef, canvas } = useFabricCanvas();
const engine = useDocumentEngine(canvas);
const state = useDocumentState(engine);
const demoRef = useRef<HTMLDivElement>(null);
// Start from a small drawing, with an empty history.
useEffect(() => {
if (!engine) return;
engine.canvas.add(...seedShapes());
engine.clearHistory();
}, [engine]);
// Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z, while focus is inside this demo.
useEffect(() => {
if (!engine || !demoRef.current) return;
return bindKeyboardShortcuts(engine, { target: demoRef.current });
}, [engine]);
function recolor() {
const target = canvas?.getActiveObject() ?? canvas?.getObjects().at(-1);
if (!engine || !target) return;
const next =
COLORS[(COLORS.indexOf(String(target.fill)) + 1) % COLORS.length];
// Fabric fires no event for `set`, so record it as one labelled step.
engine.transaction("Recolor", () => target.set("fill", next));
canvas?.requestRenderAll();
}
return (
<DemoFrame ref={demoRef} tabIndex={-1}>
<DemoCanvas elementRef={elementRef} label={t("canvas")} />
<Toolbar>
<ToolButton
icon={SquareIcon}
label={t("square")}
onClick={() => canvas?.add(newShape("square"))}
/>
<ToolButton
icon={CircleIcon}
label={t("circle")}
onClick={() => canvas?.add(newShape("circle"))}
/>
<ToolButton icon={PaletteIcon} label={t("recolor")} onClick={recolor} />
<span className="ml-auto flex gap-1.5">
<ToolButton
icon={Undo2Icon}
label={t("undo")}
iconOnly
disabled={!state?.canUndo}
onClick={() => void engine?.undo()}
/>
<ToolButton
icon={Redo2Icon}
label={t("redo")}
iconOnly
disabled={!state?.canRedo}
onClick={() => void engine?.redo()}
/>
</span>
</Toolbar>
<Status tone={state?.canUndo ? "ok" : "idle"}>
{state?.canUndo
? t("undoRedo.steps", {
count: engine?.getHistory().undo.length ?? 0,
})
: t("undoRedo.empty")}
</Status>
</DemoFrame>
);
}创建画布
Fabric.js 需要一个真实的 <canvas> 元素,所以在 effect 里创建它:
import { Canvas } from "fabric";
import { useEffect, useRef, useState } from "react";
export function useFabricCanvas(width: number, height: number) {
const elementRef = useRef<HTMLCanvasElement>(null);
const [canvas, setCanvas] = useState<Canvas | null>(null);
useEffect(() => {
const created = new Canvas(elementRef.current!, { width, height });
setCanvas(created);
return () => {
created.dispose().catch(() => undefined);
};
}, [width, height]);
return { elementRef, canvas };
}创建引擎
useDocumentEngine 在画布存在后创建引擎,并在卸载时销毁它。在此之前它返回 null:
import { bindKeyboardShortcuts } from "fabricjs-document-engine";
import {
DocumentEngineProvider,
useDocumentEngine,
} from "fabricjs-document-engine/react";
import { createLocalStorage } from "fabricjs-document-engine/storage";
import { useEffect } from "react";
const storage = createLocalStorage({ prefix: "my-app:" });
export function Editor() {
const { elementRef, canvas } = useFabricCanvas(800, 500);
const engine = useDocumentEngine(canvas, { storage, autosave: true });
useEffect(() => {
if (!engine) return;
engine.load("drawing-1").catch(() => undefined);
return bindKeyboardShortcuts(engine);
}, [engine]);
return (
<DocumentEngineProvider engine={engine}>
<Toolbar />
<canvas ref={elementRef} aria-label="Drawing canvas" />
</DocumentEngineProvider>
);
}配置项只在创建引擎时读取一次。把 storage 定义在组件外面,避免每次渲染都重新创建。
做工具栏
useEngine() 从 provider 里取出引擎,useDocumentState() 会在保存状态、历史记录或加载状态变化时重新渲染:
import { useDocumentState, useEngine } from "fabricjs-document-engine/react";
function Toolbar() {
const engine = useEngine();
const state = useDocumentState(engine);
if (!engine || !state) return null;
return (
<div role="toolbar">
<button disabled={!state.canUndo} onClick={() => engine.undo()}>
Undo {state.undoLabel}
</button>
<button disabled={!state.canRedo} onClick={() => engine.redo()}>
Redo
</button>
<button disabled={!state.isDirty} onClick={() => engine.save()}>
Save
</button>
<span aria-live="polite">{state.saveStatus}</span>
</div>
);
}监听事件
useDocumentEvent 总是使用最新的处理函数,你不用手动重新订阅:
import { useDocumentEvent } from "fabricjs-document-engine/react";
useDocumentEvent(engine, "save:error", ({ error }) => {
toast.error(`Could not save: ${error.message}`);
});StrictMode
React StrictMode 在开发环境会把 effect 执行两次。useDocumentEngine 会先销毁第一个引擎,再创建第二个,所以同时只有一个在运行。始终使用 hook 返回的引擎,这个 Fabric.js React 示例在开发和生产环境里表现一致。
Next.js 请看 Next.js 指南。所有 hooks 都列在 React hooks API 里。