我正在尝试使用 forceSimulation 用 d3 构建动态强制图。当我使用硬编码节点构建图表并链接按预期构建的所有项目时。但是当我添加新节点时,所有旧节点都不会转换它们的位置,当我拖动旧节点时,只有新节点移动(当我移动新节点时,它会按预期移动)。
我试图改变模拟的刻度方式,但没有成功解决这个问题。
var nodes = [{ "id": 0, "name": "Ego Node", "level": 0 },
{ "id": 1, "name": "first", "level": 1 },
{ "id": 2, "name": "Ego Node", "level": 2 }],
links = [{ source: 0, target: 1 },
{ source: 1, target: 2 }]
var simulation = d3.forceSimulation(nodes)
.force('charge', d3.forceManyBody().strength(-100))
.force('center', d3.forceCenter(width / 2, height / 2))
.force('link', d3.forceLink().links(links));
function update() {
var link = d3.select('.links')
.selectAll('line.link')
.data(links).enter().insert("line")
.attr("class", "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; });
link.exit().remove();
node = d3.select('.nodes')
.selectAll('g.node')
.data(nodes).enter().append("g")
.attr("class", "node");
node.append("circle")
.style("fill", function (d) {return "#0099ff"})
.attr("r", 5);
node.append("text")
.attr("class", "nodetext")
.attr("x", "0em")
.attr("y", 15)
.text(function (d) { return d.name });
node.exit().remove();
simulation.on("tick", function () {
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; });
node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
});
simulation.nodes(nodes);
simulation.force('link', d3.forceLink().links(links));
simulation.alpha(1).restart();
}
function addNode() {
nodes.push({ "Id": 3, "name": "AAA", "level": 2 });
links.push({ source: 1, target: 3 });
update();
}
当我执行 addNode() 函数时,我只能拖动添加的新节点。所有其他节点都卡住了,当我拖动它们时,它只会更改新节点的位置。任何帮助都会很棒!谢谢。