G6 是一个图可视化引擎。它提供了图的绘制、布局 g6.antv.antgroup.com/manual/layo…
- 版本
"@antv/g6": "^5.0.45",
- 使用
import { Graph, NodeEvent } from '@antv/g6'
const graph = new Graph({
container: 'container',
autoFit: 'view', // 自动适配策略,'view'(适应视图)或'center'(居中)
data:{
nodes:[], // { id: `字符串`, label: "" }
edges:[], // { source: `id`, target: `targetId` }
},
behaviors: [
// 'zoom-canvas',
'drag-canvas',
'drag-element',
], // 可以拖拽、缩放画布,拖拽节点
node: {
style: {
// labelFill: '#fff',
// labelPlacement: 'center',
labelText: (d) => d.label,
size: 30,
},
animation: {
enter: false,
},
},
edge: {
animation: {
enter: false,
},
},
layout: { // 布局
padding: 30,
type: 'snake', // force compact-box
},
})
// 添加点击事件
graph.on(NodeEvent.CLICK, async (evt) => {
console.log('graph---evt', evt.target.id)
const { id } = evt.target
const nodes = graph.getNodeData()
graph.updateData({
nodes: nodes.map(item => ({ id: item.id, style: { fill: '#1783FF' } })),
})
graph.updateData({
nodes: [{ id, style: { fill: '#07c160' } }],
})
// 更新或设置数据后,须调用 render
graph.render()
})
// 默认第一个node处于选中状态
graph.updateData({
nodes: [{ ...nodes[0], style: { fill: '#07c160' } }],
})
graph.render()