How to implement undo/redo functionality for KovaJS in react?

痴心易碎 提交于 2019-12-12 23:46:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!