2017-06-12 119 views
0

我有一个D3.js V4强制布局,其中包含由单个边链接的两个节点。一个节点靠近左上角固定,另一个节点可自由移动。D3.js v4强制布局和固定节点异常

布局运行时,非固定节点从布局中间开始,远离固定节点,就好像被排斥一样。它结束于固定节点的对角。我期望自由节点能够在布局中心(重力吸引它)和固定节点(通过链接力拉向它)之间结束。请问我错过了什么?

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>

回答

2

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

d3 Centering force documentation

定心

定心力转换节点均匀,使得所有节点的平均 位置(质量的中心,如果所有的节点具有相等 重量)是在给定的位置⟨x,y⟩。

+0

啊,谢谢。我期待它能像我在v3中使用的引力一样工作,并始终向中心拖动。我读过你所引用的一点,但没有消化它的含义。 – willw