撤消/重做像Fabric.js中的printio.ru

时间:2013-11-19 06:19:20

标签: jquery html5 canvas fabricjs

我希望在我的代码中获得像http://printio.ru/这样的撤销/重做功能,如何为我的画布编写撤消/重做。

我在我的代码中尝试了http://jsfiddle.net/SpgGV/27/但它不能完美地工作,1步撤消重做也会有效。

有什么建议吗?

var canvas = new fabric.Canvas('c');
var hw=[];
var x=0;
var current;
var list = [];
var state = [];
var index = 0;
var index2 = 0;
var action = false;
var refresh = true;
state[0] = JSON.stringify(canvas.toDatalessJSON());
console.log(JSON.stringify(canvas.toDatalessJSON()));
$("#clear").click(function(){
    canvas.clear();
    index=0;
  });
 $("#addtext").click(function(){
   ++index;
   action=true;  
 hw[x] = new fabric.Text('Sample', {
   fontFamily: 'Hoefler Text',
    left: 100,
    top: 100,
    //textAlign: 'center',
    fill: 'navy',

});

canvas.add(hw[x]); 
          x++;
}); 
canvas.on("object:added", function (e) {

    if(action===true){

        var object = e.target;
    console.log(JSON.stringify(canvas.toDatalessJSON()));
    state[index] = JSON.stringify(canvas.toDatalessJSON());
    refresh = true;
        action=false;
        canvas.renderAll();
    }
});
function undo() {

    if (index < 0) {
        index = 0;
        canvas.loadFromJSON(state[index]);
        canvas.renderAll();
        return;
    }


    console.log('undo');

    canvas.loadFromJSON(state[index]);

    console.log(JSON.stringify(canvas.toDatalessJSON()));
    canvas.renderAll();
    action = false;
}

function redo() {

    action = false;
    if (index >= state.length - 1) {
        canvas.loadFromJSON(state[index]);
        canvas.renderAll();
        return;
    }

    console.log('redo');

    canvas.loadFromJSON(state[index]);

    console.log(JSON.stringify(canvas.toDatalessJSON()));
    canvas.renderAll();

    canvas.renderAll();

}

canvas.on("object:modified", function (e) {
    var object = e.target;
    console.log('object:modified');
    console.log(JSON.stringify(canvas.toDatalessJSON()));
    state[++index] = JSON.stringify(canvas.toDatalessJSON());
    action=false;
});

$('#undo').click(function () {
    index--;
    undo();
});
$('#redo').click(function () {
    index++;
    redo();
});

0 个答案:

没有答案