我想在使用自定义布局绑定(
nodeUpdateTransform
)将某些node2移动到不同位置后在节点(node1和node2)之间绘制连接。在下面的示例中,连接被绘制到节点的原始位置。如果节点移动了,如何调整连接?
const data = [
{ customId: 1, customParentId: null, customName: 'node1' },
{ customId: 2, customParentId: 1, customName: 'node2' },
{ customId: 3, customParentId: 1, customName: 'node3' },
];
chart = new d3.OrgChart()
.nodeId((dataItem) => dataItem.customId)
.parentNodeId((dataItem) => dataItem.customParentId)
.nodeWidth((node) => 100)
.nodeHeight((node) => 100)
.nodeContent((node) => {
return `<div customId="${node.data.customId}"
style="background-color:aqua;width:${node.width}px;height:${node.height}px"
>
${node.data.customName}
</div>`;
})
.container('.chart-container')
.data(data)
.render();
i=0;
const layout = chart.layoutBindings();
layout.top.nodeUpdateTransform = function(node){
if(i==1){
i+=1;
return `translate(${(node.x-100) - node.width / 2},${node.y})`;
}
//console.log(node.parentNode);
i+=1;
return `translate(${(node.x) - node.width / 2},${node.y})`;
}
chart.layoutBindings(layout);
chart.connections([{from:"1",to:"2",label:"Conflicts of interest"}]).render();
我通过查看源代码得到了这个
d3-org-chart
。添加这一行似乎可以做到这一点:
layout.top.linkJoinX = node => node.x - 100;
运行代码:
const data = [{
customId: 1,
customParentId: null,
customName: 'node1'
},
{
customId: 2,
customParentId: 1,
customName: 'node2'
},
{
customId: 3,
customParentId: 1,
customName: 'node3'
},
];
chart = new d3.OrgChart()
.nodeId((dataItem) => dataItem.customId)
.parentNodeId((dataItem) => dataItem.customParentId)
.nodeWidth((node) => 100)
.nodeHeight((node) => 100)
.nodeContent((node) => {
return `<div customId="${node.data.customId}"
style="background-color:aqua;width:${node.width}px;height:${node.height}px"
>
${node.data.customName}
</div>`;
})
.container('.chart-container')
.data(data);
i = 0;
const layout = chart.layoutBindings();
layout.top.nodeUpdateTransform = function(node) {
if (i == 1) {
i += 1;
return `translate(${(node.x-100) - node.width / 2},${node.y})`;
}
//console.log(node.parentNode);
i += 1;
return `translate(${(node.x) - node.width / 2},${node.y})`;
}
layout.top.linkJoinX = node => node.x - 100;
chart.layoutBindings(layout);
setTimeout(function() {
chart.connections([{
from: "1",
to: "2",
label: "Conflicts of interest"
}]).render();
}, 500);
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/d3-flextree.js"></script>
<div class="chart-container"></div>