d3:计算两个节点之间的线的中点,画一条从它到一个新节点成90度角的线

d3: Calculate midpoint of line between two nodes, draw line extending at 90 degree angle from it to a new node

本文关键字:节点 一个 90度 新节点 两个 计算 之间 d3 一条      更新时间:2023-09-26

在d3中,假设有node1和node2,由水平相邻的圆表示。有一条短的水平线(我想是一条路径)连接节点1和节点2。

如何:(1) 找到该直线/路径的中点,以及(2) 为该中点指定一个新的名称或ID,我可以通过编程进行处理,这样我就可以(3) 绘制从中点到新节点3、节点4和节点5的新垂直线/路径?

您可以找到每条线的中点,并使用下面的代码绘制从该点到其他节点的线。JSFiddle

function drawLines(d){
    var x1 = nodes[d.source].x;
    var x2 = nodes[d.target].x;
    var y1 = nodes[d.source].y;
    var y2 = nodes[d.target].y;
    var otherNodes = nodes.filter(function(n,i){ return i!=d.source  || i!=d.target });
    otherNodes.forEach(function(otherNode){
         svg.append("line")
            .attr("x1",function(d){ return otherNode.x; })
            .attr("y1",function(d){ return otherNode.y; })
            .attr("x2",function(d){ return (x1+x2)/2; })
            .attr("y2",function(d){ return (y1+y2)/2; })
            .attr("class","line");
    });
}
linksEls.each(drawLines);