我正在使用 Mike Bostock 创建的原始示例在 D3 中构建分子创建器:http://bl.ocks.org/mbostock/3037015
我正在使用强制布局,就像示例中一样。我的问题是,当我动态添加新的节点/原子时,它不会随图表的其余部分一起移动。我已经阅读了其他问题并实现了建议的所有内容,并确保我遵循 D3 要求的正确更新/加入程序,但添加的碳仍然拒绝与图表的其余部分一起移动。
这是我的更新/创建函数:
function buildMolecule () {
// Update link data
link = link.data(links);
// Create new links
link.enter().append("g")
.attr("class", "link")
.each(function(d) {
d3.select(this)
.insert("line", ".node")
.style("stroke-width", function(d) { return (d.bond * 2 - 1) * 2 + "px"; });
d3.select(this)
.filter(function(d) { return d.bond > 1; }).append("line")
.attr("class", "separator");
d3.select(this)
.on("click", bondClicked);
});
// Delete removed links
link.exit().remove();
// Update node data
node = node.data(nodes);
// Create new nodes
node.enter().append("g")
.attr("class", "node")
.on("click", atomClicked)
.each(function(d) {
console.log('d:', d);
// Add node circle
d3.select(this)
.append("circle")
.attr("r", function(d) { return radius(d.size); })
.style("fill", function(d) { return color(d.atom); });
// Add atom symbol
d3.select(this)
.append("text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.atom; });
d3.select(this).call(force.drag);
});
// Delete removed nodes
node.exit().remove();
force.start();
}
JsFiddle:http://jsfiddle.net/2dPMF/1/
任何帮助将不胜感激!
最佳答案
除了添加和删除节点之外,您还修改了节点和链接的数据结构,这会扰乱力布局。我特别谈论这些行。
function bigBang () {
links = links.concat(linksList);
nodes = nodes.concat(nodesList);
buildMolecule();
}
该函数的前两行就是我所说的。工作 jsfiddle here .
关于javascript - D3.js强制布局: Dynamically added node doesn't move with rest of graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577051/