fabric-history-v7
v1.0.0
Published
Undo/Redo history plugin for Fabric.js v7
Downloads
96
Maintainers
Readme
fabric-history-v7
Undo / Redo history plugin for Fabric.js v7.
Installation
npm install fabric-history-v7Usage
Method 1 – Mixin (recommended for bundlers)
import { Canvas } from 'fabric';
import { HistoryMixin } from 'fabric-history-v7';
class MyCanvas extends HistoryMixin(Canvas) {
constructor(el, options) {
super(el, options);
this._historyInit();
}
dispose() {
this._historyDispose();
return super.dispose();
}
}
const canvas = new MyCanvas('canvas-id', options);
canvas.undo();
canvas.redo();Method 2 – Factory function (browser global)
<script src="fabric.min.js"></script>
<script type="module">
import { createCanvasWithHistory } from 'fabric-history-v7';
const CanvasWithHistory = createCanvasWithHistory(fabric.Canvas);
const canvas = new CanvasWithHistory('canvas-id');
</script>Keyboard shortcuts example
document.addEventListener('keydown', async ({ key, ctrlKey, shiftKey }) => {
if (!ctrlKey) return;
if (key === 'z') await canvas.undo();
if (key === 'y' || (shiftKey && key === 'Z')) await canvas.redo();
});API
Initialization
| Method | Description |
|---|---|
| _historyInit(extraProps?) | Initialize history. Call once in constructor after super(). |
| _historyDispose() | Remove all event listeners. Call before dispose(). |
Undo / Redo
| Method | Returns | Description |
|---|---|---|
| undo(callback?) | Promise<void> | Undo the last action. |
| redo(callback?) | Promise<void> | Redo the last undone action. |
| canUndo() | boolean | Whether there are steps to undo. |
| canRedo() | boolean | Whether there are steps to redo. |
| undoCount | number | Number of available undo steps. |
| redoCount | number | Number of available redo steps. |
History control
| Method | Description |
|---|---|
| clearHistory() | Reset undo/redo stacks to the current canvas state. |
| offHistory() | Pause history recording. |
| onHistory() | Resume recording and snapshot the current state. |
Events
| Event | Payload | Fired when |
|---|---|---|
| history:append | { json } | A new state is saved. |
| history:undo | — | After an undo is applied. |
| history:redo | — | After a redo is applied. |
| history:clear | — | History is cleared. |
canvas.on('history:append', () => console.log('saved', canvas.undoCount));
canvas.on('history:undo', () => updateButtons());
canvas.on('history:redo', () => updateButtons());Options
Pass an array of extra property names to _historyInit() to include them in
each serialized snapshot:
this._historyInit(['selectable', 'editable', 'myCustomProp']);Excluding objects from history
Set excludeFromExport = true on any fabric object to prevent changes to it
from triggering a history snapshot:
const guide = new fabric.Line([0, 0, 600, 0]);
guide.excludeFromExport = true;
canvas.add(guide); // does NOT create a history entryLicense
MIT © crayonlu
