Last active
December 12, 2023 11:55
-
-
Save alimozdemir/ae7de01eb1b741492e255b314b47383e to your computer and use it in GitHub Desktop.
Fabricjs basic history implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fabric.Canvas.prototype.historyInit = function () { | |
this.historyUndo = []; | |
this.historyNextState = this.historyNext(); | |
this.on({ | |
"object:added": this.historySaveAction, | |
"object:removed": this.historySaveAction, | |
"object:modified": this.historySaveAction | |
}) | |
} | |
fabric.Canvas.prototype.historyNext = function () { | |
return JSON.stringify(this.toDatalessJSON(this.extraProps)); | |
} | |
fabric.Canvas.prototype.historySaveAction = function () { | |
if (this.historyProcessing) | |
return; | |
const json = this.historyNextState; | |
this.historyUndo.push(json); | |
this.historyNextState = this.historyNext(); | |
} | |
fabric.Canvas.prototype.undo = function () { | |
// The undo process will render the new states of the objects | |
// Therefore, object:added and object:modified events will triggered again | |
// To ignore those events, we are setting a flag. | |
this.historyProcessing = true; | |
const history = this.historyUndo.pop(); | |
if (history) { | |
this.loadFromJSON(history).renderAll(); | |
} | |
this.historyProcessing = false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment