一、安裝使用
下載安裝:
npm install @antv/g6 --save
導入使用:
import G6 from '@antv/g6';
二、初始化畫布
1. 建立一個div
<div id="mountNode" style="margin-top: 20px;"></div>
2. js生成畫布
渲染數據格式“:
// 數據結構分為節點數組nodes和邊對應關系數組edges const data = { // 節點數組 nodes: [ { id: 'node1', x: 100, y: 200, }, { id: 'node2', x: 300, y: 200, }, ], // 邊對應關系數組 edges: [ // 從 node1 節點連接到 node2 節點的邊線 { source: 'node1', target: 'node2', }, ], };
實例化畫布:
1 methods: { 2 initG6() { 3 const nodes = this.data.nodes 5 // 創建 G6 圖實例 6 this.graph = new G6.Graph({ 7 container: 'mountNode', // 畫布容器id 8 width: 1200, // 畫布寬度 9 height: 3200, // 畫布高度 10 modes: { 11 default: ['drag-canvas','click-select'] 12 }, 13 layout: { 14 type: 'dagre', 15 rankdir: 'LR', 16 align: 'UL', 17 nodesep:15, 18 controlPoints: true, 19 }, 20 //默認節點樣式設置 21 defaultNode: { 22 size: [100, 30], 23 type: 'rect', 24 color:"#ffffff", 25 style: { 26 lineWidth: 2, 27 stroke: '#5B8FF9', 28 fill: '#C6E5FF', 29 radius:5 30 }, 31 labelCfg: { 32 style: { 33 fontSize: 12, 34 }, 35 }, 36 }, 37 // 默認的邊樣式設置 38 defaultEdge: { 39 type: 'polyline', 40 size: 1, 41 color: '#c8c8c8', 42 style: { 43 endArrow: { 44 path: 'M 0,0 L 8,4 L 8,-4 Z', 45 fill: '#c8c8c8', 46 }, 47 radius: 5, 48 }, 49 }, 50 }) 51 this.graph.data(this.data) // 讀取數據 52 this.graph.render() // 渲染數據 53 this.graph.on('click', (ev)=>{ // 監聽節點點擊事件 54 this.evt = ev.item 55 const shape = ev.target; 56 if(ev.item){ 57 const item = ev.item; 58 const type = item.getType(); 59 // console.log('點擊節點shape,item,type',shape,item,type) 60 this.selectedItem = ev.item._cfg.model 61 console.log('treecomplex click 當前節點信息',this.selectedItem) 62 }65 }); 66 if (typeof window !== 'undefined') 67 window.onresize = () => { 68 if (!this.graph || this.graph.get('destroyed')) return; 69 if (!mountNode || !mountNode.scrollWidth || !mountNode.scrollHeight) return; 70 this.graph.changeSize(mountNode.scrollWidth, mountNode.scrollHeight); 71 }; 72 }, 73 }
三、G6官方文檔