问题
What's the best way to implement undo/redo functionality for KovaJS in react?
I see that each node has toObject() method used for serialisation of each canvas node. One easy implementation would be to serialize the object on each modification and push it into a array of changes. And once the user taps Undo/Redo, to try and rebuild the canvas from that array.
Any thoughts?
回答1:
You don't need to use toObject()
if you are using React.
It will be much simpler to save a history of the state (react component state, redux state or whatever state you are using). And implement undo/redo with it.
Simplest demo for undo:
let history = [{
x: 20,
y: 20
}];
let historyStep = 0;
class App extends Component {
state = {
position: history[0]
};
handleUndo = () => {
if (historyStep === 0) {
return;
}
historyStep -= 1;
this.setState({
position: history[historyStep]
});
};
handleDragEnd = e => {
history.slice(0, historyStep);
history = history.concat({
x: e.target.x(),
y: e.target.y()
});
historyStep += 1;
console.log(history[history.length - 1]);
this.setState({
position: history[history.length - 1]
});
};
render() {
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text text="undo" onClick={this.handleUndo} />
<Rect
x={this.state.position.x}
y={this.state.position.y}
width={50}
height={50}
fill="black"
draggable
onDragEnd={this.handleDragEnd}
/>
</Layer>
</Stage>
);
}
}
https://codesandbox.io/s/3x3rwnlykp
来源:https://stackoverflow.com/questions/50406640/how-to-implement-undo-redo-functionality-for-kovajs-in-react