2013-05-03 98 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