在 registerNode 中定义所有的节点
G6.registerNode('tree-node', {drawShape: function drawShape(cfg, group) {定义图中需要的节点}
}, 'single-node',);
为了使用内置的布局方式,选择参数为 ‘tree-node’ 树节点类型,数据格式可以存在children子节点,效果自动生成子树
cfg 可以拿到数据,如cfg.id、cfg.name
使用 group.addShape(‘rect’, {}) 定义节点 rect
配置参数:https://antv-g6.gitee.io/zh/docs/api/shapeProperties/#fill
// 定义节点 rect const rect = group.addShape('rect', { // 'rect'表示矩形图形attrs: {// 节点定义参数:颜色、阴影...},name: 'rect-shape', // 为这个节点起名字 不过没有使用过这个名字});
使用 group.addShape(‘text’, {}) 定义文本 text
// 定义文本textconst text = group.addShape('text', { // 'text'表示文本attrs: {// 参数:颜色、文字...},name: 'text-shape',});
节点和文字生成后,再定义他们的相对位置
参考官网定义复杂图样式的方式:https://antv-g6.gitee.io/zh/examples/tree/customItemTree#customTree
使用 .getBBox() 获得该文本的盒子bbox,使用文本盒子的相对位置后面的位置坐标
const bbox = text.getBBox(); // 获得文本的盒子// 设置rect 节点的位置rect.attr({x: -bbox.width / 2 - 5, // x坐标y: -bbox.height, // y坐标width: bbox.width + 12 , // 宽height: bbox.height + 8, // 高});// 设置text文本的位置text.attr({x: -bbox.width / 2,y: -bbox.height / 2 + 3,})
效果如下
如果想为节点再增加一个小节点,并且位置随着大节点移动,如图
新增节点和文本 rect2 text2
rect2 = group.addShape('rect', {attrs: {// 参数},name: 'rect-shape2',
});
const text2 = group.addShape('text', {attrs: {// 参数},name: 'text-shape2',
});
为rect2 text2设置坐标,以bbox作为参考位置
// 设置坐标轴和宽高rect2.attr({x: -bbox.width / 2 - 24,y: -bbox.height / 2 - 1,width: 14,height: 10,});text2.attr({x: -bbox.width / 2 - 23,y: -bbox.height / 2 + 4,})
roup.addShape('dom', {attrs: {x: -bbox.width / 2 - 24 + 14, // 即:rect的坐标 + rect的宽 y: -bbox.height / 2 - 1,width: 10,height: 10,html: `自定义dom`,},draggable: true,});
使用自定义dom,在 new G6.TreeGraph中 需要设置
renderer : 'svg', // 奇怪的是设置之后原来节点的布局有些影响
renderer : 'svg',
https://antv-g6.gitee.io/zh/docs/manual/middle/states/defaultBehavior#%E5%86%85%E7%BD%AE-behavior
modes: {default: [{type: 'collapse-expand',onChange: function onChange(item, collapsed) {const data = item.get('model');graph.updateItem(item, {collapsed,});data.collapsed = collapsed;return true;},},'drag-canvas', // 允许拖动'zoom-canvas', // ....],},
defaultEdge: {type: 'cubic-horizontal',style: {stroke: 'red' //红色},},
https://antv-g6.gitee.io/zh/docs/manual/middle/layout/tree-graph-layout
layout: {type: 'indented',direction: 'LR', // 节点从左向右分布dropCap: false,indent: 190,getHeight: () => {return 13;},getVGap: function getVGap () {return 10;},},