0

I've achieved with other's solutions to undo & redo functions on a fabric js canvas (change size of rectangle and set it as previously, move and move it as previously...).

I have a project where I can import different prebuilded canvas, which are stored on JSONs files, but when I imported them, and (for example) I move a rectangle which was inside the JSON, and then I click "undo", it doesn't come back to the previous position but it deletes the whole previous canvas, clearing it all.

I think this should be an issue with what the canvas considers the previous state before the JSON import, which was a clear canvas. But I'm trying different solutions and it doesn't seem to work... Any ideas?

This is my code now:

canvas.counter = 0;
var state = [];
var mods = 0;
canvas.on(
  'object:modified',
  function () {
    updateModifications(true);
  },
  'object:added',
  function () {
    updateModifications(true);
  });

function updateModifications(savehistory) {
  if (savehistory === true) {
    myjson = JSON.stringify(canvas);
    state.push(myjson);
  }
}

document.getElementById("undobtn").onclick = () => {
  console.log("undoing")
  if (mods < state.length) {
    canvas.clear().renderAll();
    canvas.loadFromJSON(state[state.length - 1 - mods - 1]);
    canvas.renderAll();
    //console.log("geladen " + (state.length-1-mods-1));
    //console.log("state " + state.length);
    mods += 1;
    //console.log("mods " + mods);
  }
}

document.getElementById("redobtn").onclick = () => {
  if (mods > 0) {
    canvas.clear().renderAll();
    canvas.loadFromJSON(state[state.length - 1 - mods + 1]);
    canvas.renderAll();
    //console.log("geladen " + (state.length-1-mods+1));
    mods -= 1;
    //console.log("state " + state.length);
    //console.log("mods " + mods);
  }
}
  • I've found the problem. When a canvas is imported by "loadFromJSON", should be necessary to do a "updateModifications(true)" to register the actual state of the canvas, so it can be able to know which was the first state of it. – Albert Badias Nov 28 '22 at 18:54

0 Answers0