2021年11月11日更新:
发现好多同学在问G6的一些相关问题,本人也一年没碰G6了,很多问题无法给予正确的回答,这里建议大家好好去看下G6的源码,从G6是如何创建节点开始,相信大家收获会更多
以下为原文:
自定义节点有两种:
1,svg + 自定义 DOM ,
缺点:不支持G6事件
G6.registerNode('dom-node', {
draw: (cfg, group) => {
const shape = group.addShape('dom', {
attrs: {
width: cfg.size[0],
height: cfg.size[1],
html: `
<div id=${cfg.id} class='dom-node' style="background-color: #fff; border: 2px solid ${stroke}; border-radius: 5px; width: ${cfg.size[0] - 5}px; height: ${cfg.size[1] - 5}px; display: flex;">
<div style="height: 100%; width: 33%; background-color: #CDDDFD">
<img alt="" style="line-height: 100%; margin-left: 7px;" src="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ" width="20" height="20" />
</div>
<span style="margin:auto; padding:auto; color: #5B8FF9">${cfg.label}</span>
</div>
`
},
});
return shape;
}
});
2.采用属性的方式来创建
会按照addShape顺序来解析节点
G6.registerNode('rectNode', {
draw: (cfg, group) => {
//最外面的那层
const shape = group.addShape('rect', {
draggable: true,
attrs: {
x: 0,
y: 0,
width: 125,
height: 40,
fill: cfg.style.fill, //填充色
stroke: '', //边框
radius: 8,
},
});
//里面的那层
group.addShape('rect', {
draggable: true,
attrs: {
x: 5,
y: 0,
width: 120,
height: 40,
fill: '#fff', //填充色
stroke: '', //边框
radius: 6,
},
});
//文字
group.addShape('text', {
attrs: {
// textBaseline: 'center',
y: 25,
x: 24,
lineHeight: 10,
text: cfg.label,
fill: '#000',
},
});
return shape;
},
});
效果图: