Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - How to create Undo-Redo in kineticjs?

Is there any simple way how to create undo redo function in Kineticjs ? I have found a Undo Manager for HTML 5 in https://github.com/ArthurClemens/Javascript-Undo-Manager, but I don't know how to put in Kineticjs, please help me. thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was able to implement a simple solution based on a post by Chtiwi Malek at CodiCode. I also used some of the code from this problem as an example to draw rectangles, so credits go to them and Chtiwi.

The only difference in my solution is I used toJSON() to store each layer state in an array instead of toDataURL() on the canvas. I think toJSON() is needed over toDataURL() to be able to serialize all the data necessary to store each action on the canvas, but I'm not 100% on this so if someone else knows please leave a comment.

function makeHistory() {
    historyStep++;
    if (historyStep < history.length) {
        history.length = historyStep;
    }
    json = layer.toJSON();
    history.push(json);
}

Call this function everytime you want to save a step to undo or redo. In my case, I call this function on every mouseup event.

Bind these 2 functions to the Undo/Redo events.

function undoHistory() {
    if (historyStep > 0) {
        historyStep--;
        layer.destroy();
        layer = Kinetic.Node.create(history[historyStep], 'container')
        stage.add(layer);
    }
}

function redoHistory() {
    if (historyStep < history.length-1) {
        historyStep++;
        layer.destroy();
        layer = Kinetic.Node.create(history[historyStep], 'container')
        stage.add(layer);
    }
}

Here's the jsfiddle. Don't forget to initialize the array and step counter up top. Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...