Undo Redo for Fabric.js

gco picture gco · Mar 11, 2014 · Viewed 12.2k times · Source

I'm trying to add undo/redo functionality to my Fabric.js canvas. My idea is to have a counter which counts canvas modifications (right now it counts the addition of objects). I have a state array, which pushes the whole canvas as JSON to my array.

Then I simply want to recall the states with

canvas.loadFromJSON(state[state.length - 1 + ctr],

As the user clicks on undo, ctr will reduce by one and load the state out of the array; as the user clicks on redo, ctr will increase by one and load the state out of the array.

When I experience this with simple numbers, everything works fine. With the real fabric canvas, I get some troubles --> it doesnt really work. I think this relies on my event handler

canvas.on({
   'object:added': countmods
});

jsfiddle is here:

here is the working numbers only example (results see console): jsFiddle

Answer

gco picture gco · Apr 22, 2014

I answered this on my own.

See jsfiddle:

What I did:

if (savehistory === true) {
    myjson = JSON.stringify(canvas);
    state.push(myjson);
} // this will save the history of all modifications into the state array, if enabled

if (mods < state.length) {
    canvas.clear().renderAll();
    canvas.loadFromJSON(state[state.length - 1 - mods - 1]);
    canvas.renderAll();
    mods += 1;
} // this will execute the undo and increase a modifications variable so we know where we are currently. Vice versa works the redo function.

Would still need an improvement to handle both drawings and objects. But that should be simple.