2013-05-03 55 views
6

使用强制导向图,当目标和源是同一节点时,如何获得实际显示的链接。所以基本上只是一个很好的小循环,表明存在这样一个边缘。D3 Force布局图 - 自连接节点

有迹象表明,我已经使用或试图使用两个D3的例子:

+0

您需要定义一个适当的路径(“d”属性)的自引用节点,即有中间点和适当插值的东西。 – 2013-05-03 20:32:08

回答

14

诀窍是绘制自链接作为一个弧形的路径。我花了一些时间来处理arc parameter syntax,让事情奏效,关键似乎是弧线无法在同一点开始和结束。以下是在每次更新时绘制边缘的相关代码。

function tick() { 
    link.attr("d", function(d) { 
    var x1 = d.source.x, 
     y1 = d.source.y, 
     x2 = d.target.x, 
     y2 = d.target.y, 
     dx = x2 - x1, 
     dy = y2 - y1, 
     dr = Math.sqrt(dx * dx + dy * dy), 

     // Defaults for normal edge. 
     drx = dr, 
     dry = dr, 
     xRotation = 0, // degrees 
     largeArc = 0, // 1 or 0 
     sweep = 1; // 1 or 0 

     // Self edge. 
     if (x1 === x2 && y1 === y2) { 
     // Fiddle with this angle to get loop oriented. 
     xRotation = -45; 

     // Needs to be 1. 
     largeArc = 1; 

     // Change sweep to change orientation of loop. 
     //sweep = 0; 

     // Make drx and dry different to get an ellipse 
     // instead of a circle. 
     drx = 30; 
     dry = 20; 

     // For whatever reason the arc collapses to a point if the beginning 
     // and ending points of the arc are the same, so kludge it. 
     x2 = x2 + 1; 
     y2 = y2 + 1; 
     } 

return "M" + x1 + "," + y1 + "A" + drx + "," + dry + " " + xRotation + "," + largeArc + "," + sweep + " " + x2 + "," + y2; 
}); 

这里是a jsfiddle演示了整个事情,并截图:

enter image description here

+0

只需添加;如果你想让其余的链接只是普通的直接链接,可以将'drx'和'dry'设置为'0'来获得正常的链接:) – 2017-04-14 18:23:19