Fabric.js 一次导致 2 个步骤的撤消重做功能

Fabric.js Undo Redo Functionality causing 2 steps at a time

当我使用多种方法添加对象时,我在 Undo/Redo 工作时遇到了一些问题。我的编辑器有一个按钮可以添加图像、背景和文本。

因此,我相信(如果我错了请纠正我)我需要在每次调用添加图像、背景或文本的函数时调用 updateModifications() 函数,以及每次 canvas 被修改。我相当确定问题是在整个文档中 updateModifications 被调用了太多次。

function remove(){
  console.log(canvas.getActiveObject());
  var activeObjects = canvas.getActiveObjects();
      canvas.discardActiveObject()
      if (activeObjects.length) {
        canvas.remove.apply(canvas, activeObjects);
      }
      updateModifications(true);
}
canvas.on({
  'object:modified': function () {
    updateModifications(true);
  },
  'object:added': function() {
    updateModifications(true);
  }

});
function addText() {
  prodName = localStorage.getItem('storedName');
  var textObj = new fabric.IText(prodName, {
    fontSize: 22,
    top: 362.5,
    left: 262.5,
    hasControls: true,
    fontWeight: 'bold',
    fontFamily: '"Montserrat",sans-serif',
    fontStyle: 'normal',
    centeredrotation: true,
    originX: 'center',
    originY: 'center'
  });
  canvas.insertAt(textObj,0).setActiveObject(textObj);
  textToFront();
  canvas.renderAll();
  updateModifications(true);
}

这在代码 ;

时造成了一些问题
var mods = 0;
var state = [];
function updateModifications(savehistory) {
  if (savehistory === true) {
      myjson = JSON.stringify(canvas);
      state.push(myjson);
  }
}

undo = function undo() {
  if (mods < state.length) {
      canvas.clear().renderAll();
      canvas.loadFromJSON(state[state.length - 1 - mods - 1]);
      canvas.renderAll();
      mods += 1;
  }
}

redo = function redo() {
  if (mods > 0) {
      canvas.clear().renderAll();
      canvas.loadFromJSON(state[state.length - 1 - mods + 1]);
      canvas.renderAll();
      mods -= 1;
  }
}

当您调用 addText() 时,您正在调用 updateModifications(),然后有一个事件侦听器 'object:added' 也调用 updateModifications()。要么删除事件侦听器,要么干脆不在 addText() 中调用 updateModifications()。

不确定然后交配,但这在 fabric 2.5 中对我有用:

var CanvasState = [];
var CanvasStateIndex = -1;
saveCanvas()

function refreshCanvas(){
  canvas.renderAll.bind(canvas);
}

function saveCanvas(){
  var newState = canvas.toJSON();
  CanvasState.push(newState);
  CanvasStateIndex = CanvasStateIndex +1;
  while (CanvasStateIndex < (CanvasState.length)-1){
    CanvasState.pop();
  }
}

function undo(){
  if (CanvasStateIndex >= 0){
    CanvasStateIndex = CanvasStateIndex -1;
    var jsonCanvas = CanvasState[CanvasStateIndex];
    canvas.loadFromJSON(jsonCanvas, refreshCanvas, function(o, obj){ 
    })
  } else{
    console.log('undo error CanvasStateIndex = '+CanvasStateIndex)
  }
}

function redo(){
  if (CanvasStateIndex < CanvasState.length -1){
    CanvasStateIndex = CanvasStateIndex +1;
    var jsonCanvas = CanvasState[CanvasStateIndex];
    canvas.loadFromJSON(jsonCanvas, refreshCanvas, function(o, obj){
    })
  }else{
    console.log('redo error CanvasStateIndex = '+CanvasStateIndex)
  }
};