-
-
Save abods/86dec4bf111605d282cfdcddf3af1646 to your computer and use it in GitHub Desktop.
History implementation for fabricJS
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
function (canvas, container) { | |
var history = {state: [], lock: true, mods: 0}; | |
app.history = history; | |
canvas.on('history.lock', function () { | |
history.lock = true; | |
}); | |
canvas.on('history.unlock', function () { | |
history.lock = false; | |
}); | |
canvas.on('history.clear', function () { | |
history.state = []; | |
history.mods = 0; | |
}); | |
canvas.on('history:modified', function () { | |
updateModifications(); | |
}); | |
canvas.on('objects:loaded', function () { | |
history.lock = false; | |
updateModifications(); | |
}); | |
canvas.on('object:added', function () { | |
updateModifications(); | |
}); | |
canvas.on('object:removed', function () { | |
updateModifications(); | |
}); | |
canvas.on('object:modified', function () { | |
updateModifications(); | |
}); | |
function updateModifications() { | |
if (!history.lock) { | |
var json = canvas.toJSON(); | |
if (history.mods > 0) { | |
history.state = history.state.slice(0, history.state.length - history.mods); | |
history.mods = 0 | |
} | |
history.state.push(json); | |
updateBtnsStyle(); | |
} | |
} | |
function undo() { | |
if (history.mods < history.state.length - 1) { | |
loadState(history.state[history.state.length - history.mods - 2]); | |
history.mods += 1; | |
updateBtnsStyle(); | |
} | |
} | |
function redo() { | |
if (history.mods > 0) { | |
loadState(history.state[history.state.length - history.mods]); | |
history.mods -= 1; | |
updateBtnsStyle(); | |
} | |
} | |
function loadState(state) { | |
history.lock = true; | |
canvas.clear().renderAll(); | |
canvas.loadFromJSON(state, function () { | |
canvas.renderAll(); | |
canvas.trigger('history:update'); | |
history.lock = false; | |
}); | |
} | |
function updateBtnsStyle() { | |
if ((history.mods < history.state.length - 1)) { | |
container.find('#history-undo').removeClass('disable'); | |
} else { | |
container.find('#history-undo').addClass('disable'); | |
} | |
if (history.state.length > 1 && history.mods > 0) { | |
container.find('#history-redo').removeClass('disable'); | |
} else { | |
container.find('#history-redo').addClass('disable'); | |
} | |
} | |
container.find('#history-undo').click(function (e) { | |
undo(); | |
e.preventDefault(e); | |
return false; | |
}); | |
container.find('#history-redo').click(function (e) { | |
redo(); | |
e.preventDefault(e); | |
return false; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment