我正在使用 d3 强制布局。我必须根据我拥有的数据显示节点和节点之间的链接。我正在使用数据设置圆的属性 cx 和 cy。圆圈显示在正确的坐标处,但节点数据中的 dx 和 dy 未更新。在刻度函数中,源和目标具有相同的坐标。所以,我无法在两个节点之间画一条线。
var nodes = [{ id: 1, type: 'startNode', shape: 'circle', fixed: true},{ id: 2, type: 'endNode', shape: 'circle', fixed: true}],
links = [{ source: nodes[0], target: nodes[1]}];
//force layout init
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([width, height])
.linkDistance(150)
.charge(-500)
.on('tick', tick)
var pathElements = svg.append('svg:g').selectAll('path')
nodeElements = svg.append('svg:g').selectAll('g');
function restart(){
pathElements = pathElements.data(links);
pathElements.enter().append('svg:path')
.attr('class', 'link')
nodeElements = nodeElements.data(nodes, function(d){
return d.id;
});
var g = nodeElements.enter().append("svg:g")
g.append("svg:circle")
.attr('r','40')
.attr('class','node')
.attr('cx',function(d){
console.log(d.id)
return 100 * d.id;
})
.attr('cy',function(d){
return 100 * d.id;
})
force.start();
}
function tick() {
pathElements.attr('d', function(d) {
return 'M' + (d.source.x )+ ',' + (d.source.y) + 'L' + (d.target.x) + ',' + (d.target.y);
});
}