如何在反应中实现KovaJS的撤消/重做功能?

时间:2018-05-18 08:07:03

标签: konvajs

在反应中为KovaJS实现撤消/重做功能的最佳方法是什么?

我看到每个节点都有toObject()方法用于每个canvas节点的序列化。一个简单的实现是在每个修改上序列化对象并将其推送到一组更改中。一旦用户点击撤消/重做,尝试从该阵列重建画布。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的是React,则不需要使用toObject()

保存状态历史(反应组件状态,还原状态或您正在使用的任何状态)将更加简单。并用它实现撤消/重做。

最简单的撤消演示:

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