【问题标题】:D3 Force Layout Graph - Self linking nodeD3 Force Layout Graph - 自链接节点
【发布时间】:2013-04-27 20:33:43
【问题描述】:

使用力有向图,当目标和源是同一个节点时,如何获得实际显示的链接。所以基本上只是一个漂亮的小循环,表明存在这样的边缘。

有两个我已经使用或尝试使用的 D3 示例:

【问题讨论】:

  • 您需要为自引用节点定义适当的路径(“d”属性),即具有中间点和合适插值的路径。

标签: d3.js force-layout


【解决方案1】:

诀窍是将自我链接绘制为带有弧线的路径。我花了一些时间摆弄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,它演示了整个事情,还有一个屏幕截图:

【讨论】:

  • 只是添加;如果您希望其余链接只是普通的直接链接,请将 drxdry 设置为 0 以获得普通链接:)
  • 让这个链接避免与其他节点重叠会很有趣,不确定这是否允许但真的很感激这个例子
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
相关资源
最近更新 更多