D3.js v4强制布局和固定节点异常

时间:2017-06-12 19:46:58

标签: d3.js

我有一个D3.js V4 Force布局,包括由单个边连接的两个节点。一个节点固定在左上角附近,另一个节点可自由移动。

当布局运行时,非固定节点在布局的中间开始,并远离固定节点,就像被击退一样。它最终位于固定节点的对角。

我希望自由节点在布局的中心(重力拉动它)和固定节点(通过链接力拉向它)之间结束。我想念的是什么?



var width = 240,
  height = 150;
var nodes = [
  { // Larger node, fixed
    fx: 20,  fy: 20,  r: 10
  }, 
  { // Small node, free
    r: 5
  }];
var links = [{ // Link the two nodes
    source: 0,    target: 1
  } 
];
var svg = d3.select('body').append('svg')
  .attr('width', width)
  .attr('height', height);
// Create simulation with layout-centring and link forces
var force = d3.forceSimulation()
  .force("centre", d3.forceCenter(width / 2, height / 2))
  .force("link", d3.forceLink())
  .nodes(nodes);
force.force("link").links(links);

// Draw stuff
var link = svg.selectAll('.link')
  .data(links)
  .enter().append('line')
  .attr('class', 'link');
var node = svg.selectAll('.node')
  .data(nodes)
  .enter().append('circle')
  .attr('class', 'node')
force.on('tick', function() {
  node.attr('r', function(d) {
      return d.r;
    })
    .attr('cx', function(d) {
      return d.x;
    })
    .attr('cy', function(d) {
      return d.y;
    });
  link.attr('x1', function(d) {
      return d.source.x;
    })
    .attr('y1', function(d) {
      return d.source.y;
    })
    .attr('x2', function(d) {
      return d.target.x;
    })
    .attr('y2', function(d) {
      return d.target.y;
    });
});

<script src="https://d3js.org/d3.v4.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <style>
    .node {
      fill: #f00;
      stroke: #fff;
      stroke-width: 2px;
    }
    
    .link {
      stroke: #777;
      stroke-width: 2px;
    }
  </style>
</head>

<body>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

中心力将尝试在给定的坐标中具有所有节点的质心。由于您有2个节点且1个是固定的,因此另一个节点将与固定节点对称。

d3 Centering force documentation

  

定心

     

定心力均匀地转换节点以便均值   所有节点的位置(质心,如果所有节点都相等)   权重)在给定位置⟨x,y⟩。

相关问题