安装
npm install @antv/g6 --save
引用
import G6 from '@antv/g6'
自定义节点
/**
* 方式一
*/
G6.registerNode('rect-jsx', (cfg) =>`
<group>
<rect>
<rect style={{
width: 160,
height: 20,
fill: ${cfg.color},
cursor: 'move',
stroke: ${cfg.color}
}} draggable="true">
<text style={{
marginTop: 2,
marginLeft: 75,
textAlign: 'center',
fontWeight: 'bold',
fill: '#333' }}>自定义文字</text>
</rect>
<rect style={{
width: 160,
height: 55,
stroke: ${cfg.color},
fill: ${cfg.color},
}} draggable="true">
<text style={{ marginTop: 5, marginLeft: 3, fill: '#333', marginLeft: 4 }}> {{label}}</text>
<text style={{ marginTop: 10, marginLeft: 3, fill: '#333', marginLeft: 4 }}>{{statusDesc}}</text>
</rect>
</group>
`)
/**
* 方式二
*/
G6.registerNode(
'card-node',
{
drawShape: function drawShape(cfg, group) {
const color = cfg.error ? '#F4664A' : '#30BF78';
const r = 2;
const shape = group.addShape('rect', {
attrs: {
x: 0,
y: 0,
width: 200,
height: 60,
stroke: color,
radius: r,
},
name: 'main-box',
draggable: true,
});
group.addShape('rect', {
attrs: {
x: 0,
y: 0,
width: 200,
height: 20,
fill: color,
radius: [r, r, 0, 0],
},
name: 'title-box',
draggable: true,
});
// left icon
group.addShape('image', {
attrs: {
x: 4,
y: 2,
height: 16,
width: 16,
cursor: 'pointer',
img: ICON_MAP[cfg.nodeType || 'app'],
},
name: 'node-icon',
});
// title text
group.addShape('text', {
attrs: {
textBaseline: 'top',
y: 2,
x: 24,
lineHeight: 20,
text: cfg.title,
fill: '#fff',
},
name: 'title',
});
if (cfg.nodeLevel > 0) {
group.addShape('marker', {
attrs: {
x: 184,
y: 30,
r: 6,
cursor: 'pointer',
symbol: cfg.collapse ? G6.Marker.expand : G6.Marker.collapse,
stroke: '#666',
lineWidth: 1,
},
name: 'collapse-icon',
});
}
// The content list
cfg.panels.forEach((item, index) => {
// name text
group.addShape('text', {
attrs: {
textBaseline: 'top',
y: 25,
x: 24 + index * 60,
lineHeight: 20,
text: item.title,
fill: 'rgba(0,0,0, 0.4)',
},
name: `index-title-${index}`,
});
// value text
group.addShape('text', {
attrs: {
textBaseline: 'top',
y: 42,
x: 24 + index * 60,
lineHeight: 20,
text: item.value,
fill: '#595959',
},
name: `index-title-${index}`,
});
});
return shape;
},
},
'single-node',
);
绑定事件
graph.on('aftercreateedge', e => {
})
graph.on('click', (evt) => {
});
graph.on('node:dblclick', evt => {
})
连线控制
{
type: 'create-edge',
trigger: 'click',
key: 'shift',
shouldBegin: e => {
this.setState({begin: e.item._cfg.id})
return true
},
shouldEnd: e => {
let flag = true
this.state.edges.forEach(item => {
if (this.state.begin === item.source) {
if (e.item._cfg.id === item.target) {
flag = false
}
}
})
return flag
}
根据坐标返回位置信息
const { item } = evt
const model = item.getModel()
const { x, y } = model
const point = graph.getCanvasByPoint(x, y)
注意事项
在数据源多次变化时先需要销毁画布
this.graph.destroy()
详细的边文字、节点提示等等,官方文档介绍的很多,这里介绍React的简单实现,供大家少走弯路。官方链接:https://g6.antv.vision/zh