【问题标题】:d3: Calculate midpoint of line between two nodes, draw line extending at 90 degree angle from it to a new noded3:计算两个节点之间的线的中点,绘制从它延伸到新节点的90度角线
【发布时间】:2014-11-11 05:51:03
【问题描述】:

在d3中,假设有node1和node2,用水平相邻的圆圈表示。有一条短的水平线(我猜是路径)连接 node1 和 node2。

我该如何: (1) 找到那条线/路径的中点,并且 (2) 给该中点一个新的名称或 ID,我可以通过编程方式使用它,这样我就可以 (3) 绘制从中点到新节点 3、节点 4 和节点 5 的新垂直线/路径?

【问题讨论】:

  • 不熟悉 d3 但你可以通过将两个端点相加并除以 2 来找到 ANY 线的中点
  • 提供一些代码来展示您到目前为止所尝试的内容总是很有用的。这实际上是一个基本的三角学问题,并非特定于 d3。

标签: javascript d3.js


【解决方案1】:

您可以使用下面的代码找到每条线的中点并从该点画线到其他节点。 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多