初探G6, 切換資料時保證圖位置不變

or_so發表於2018-12-19

codepen

 const data = {
  nodes: [{
    id: '收集日誌',
    label: 'aaa',
  }, {
    id: '入 es 叢集',
    label: 'bbb',
  }, {
    id: '入 hdfs',
    label: 'ccc',
  }, {
    id: 'hive 計算',
    label: 'ddd',
  }, {
    id: 'report',
    label: 'eee',
  }],
  edges: [{
    source: '收集日誌',
    target: '入 es 叢集'
  }, {
    source: '收集日誌',
    target: '入 hdfs'
  }, {
    source: '入 hdfs',
    target: 'hive 計算'
  }, {
    source: '入 es 叢集',
    target: 'hive 計算'
  }, {
    source: 'hive 計算',
    target: 'report'
  }]
};
       const datas = {
  nodes: [{
    id: '收集日誌',
    label: 111,
  }, {
    id: '入 es 叢集',
    label: 222,
  }, {
    id: '入 hdfs',
    label: 333,
  }, {
    id: 'hive 計算',
    label: 444,
  }, {
    id: 'report',
    label: 555,
  }],
  edges: [{
    source: '收集日誌',
    target: '入 es 叢集'
  }, {
    source: '收集日誌',
    target: '入 hdfs'
  }, {
    source: '入 hdfs',
    target: 'hive 計算'
  }, {
    source: '入 es 叢集',
    target: 'hive 計算'
  }, {
    source: 'hive 計算',
    target: 'report'
  }]
};
class IntroCard extends React.Component {
  constructor(props) {
        super(props);
        this.state = {
            showImage: true,
        };
        this.graph = null;
    }
  componentDidMount() {
      this.rendeG6(data);
    }
    rendeG6 = (data) => {
  this.graph= new G6.Graph({
  container: 'mountNode',
  // fitView: 'cc',
  height: window.innerHeight, // 畫布高
  plugins: [new G6.Plugins['layout.dagre']()],
  defaultIntersectBox: 'rect' // 使用矩形包圍盒
});

this.graph.node({
  shape: 'rect',
  label: function label(model) {
    return model.label;
  },

  style: {
    stroke: '#00C0A5',
    fill: '#92949F',
    fillOpacity: 0.45,
    lineWidth: 2
  }
});
this.graph.edge({
  style: {
    endArrow: true
  }
});
      let lastPoint = 0;
        this.graph.on('drag', (ev) => {
          this.graph.css({
            cursor: 'pointer',
          });
          if (lastPoint) {
            this.graph.translate(ev.domX - lastPoint.x, ev.domY - lastPoint.y);
          }
          lastPoint = {
            x: ev.domX,
            y: ev.domY,
          };
        });
        this.graph.on('dragend', () => {
          this.graph.css({
            cursor: 'default',
          });
          lastPoint = undefined;
        });
this.graph.read(data);
    }
    onload = () => {
      this.graph.read(datas);
    }
    onback = () => {
       this.graph.read(data);
    }
  render() {
    return (
      <div>
        <button onClick={this.onload}>切換資料</button>
        <button onClick={this.onback}>後設資料</button>
        <div id="mountNode"></div>
       </div>
    )
  }

};
複製程式碼

codepen地址

相關文章