D3非定向层次关系图算法布局思路
- 纵向非定向层次关系图,纵向节点元素间的间距:YSpacing
1.由前一个兄弟节点的位置Y + 前一个兄弟节点的子节点个数/2YSpacing +自己子节点个数/2YSpacing
treeNodes.forEach((list, i) => {
list.forEach((node, j) => {
if (j > 0) {
const ownLen = getChildNode(treeNodes[i + 1], treeEdges, node.id).length
const brother = getChildNode(treeNodes[i + 1], treeEdges, list[j - 1].id).length
node.y = list[j - 1].y + (ownLen + brother) / 2 * YSpacing
}
})
})
2.树状层次关系图形成之后,让父节点居中
// 父节点居中
for (let i = maxIndex - 1; i > -1; i--) {
const list = treeNodes[i]
list.forEach((node) => {
const ownLen = getChildNode(treeNodes[i + 1], treeEdges, node.id)
if (ownLen.length > 1) {
node.y = (ownLen[0].y + ownLen[ownLen.length - 1].y) / 2
}
})
}