我forceSimulation
的定义是这样的:
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(function (d) {
return Math.max(12* (d.target.r), 600);
}))
.force("charge", d3.forceManyBody().strength(function() { return -100}))
.force("center", d3.forceCenter(width / 2, height/ 2))
.force("collide", d3.forceCollide().radius(function(d){return d.r}).strength(1));
在我的代码中,每当forceSimulation
发生变化时,我都会调用以下绘制函数。
function draw(graphNodes,graphLinks) {
console.log("DRAWING");
console.log(graphNodes);
console.log(graphLinks);
graphLinks = mergeLinks(graphLinks);
//Update the visualisation
link = link.selectAll(".line").data(graphLinks);
//Exit should come first
link.exit().remove();
link = link.enter().append("line")
.attr("stroke-width", 5)
.attr("class", "link")
.attr("stroke", function(d){ return getLineColor(d)});
node = node.selectAll("circle").data(graphNodes);
//Exit should come frist
node.exit().remove();
node = node.enter().append("circle")
.attr("r", function(d) {
var rad = getNodeRadius(d, graphLinks);
d.r = rad;
return rad})
.attr("fill", function(d) { return getNodeColor(d); })
.attr("class", "node")
.attr("id", function(d) { return d.id});
//Create the foreignObjects for the text or images
img = img.selectAll("bookimage").data(graphNodes);
img.exit().remove();
img = img.enter().append("foreignObject")
.attr("width", function (d) { return d.r*2})
.attr("height", function(d) { return d.r*2})
.attr("x", function(d){return (d.x )})
.attr("y", function(d){return (d.y )});
//Create the content in the nodes
img.append("xhtml:div")
.attr("class", "img")
.style("font", "14px 'Helvetica Neue'")
.attr("id", function(d) { return d.id + "T"})
.html(function(d) {return getBookImage(d)});
txt = txt.selectAll("label").data(graphLinks);
txt.exit().remove();
txt = txt.enter().append("text")
.attr("fill", "#FFF")
.attr("text-anchor", "middle")
.attr("font-family", "helvetica")
.text(function(d) { return d.name })
.each(function(d) {
d.width = this.getComputedTextLength();
});
simulation.nodes(graphNodes).on("tick", ticked);
simulation.force("link").links(graphLinks);
//If there are new nodes, or the books are moved restart the visualisation
if (visRestart) {
//RESTART THE VISUALISATION
visRestart = false;
console.log("RESTART");
simulation.alpha(1).restart();
}
}
使用不同的graphNodes
和graphLinks
调用此函数(我已检查过print语句),但可视化永远不会更改。有什么帮助吗?
答案 0 :(得分:0)
由于forceSimulation
是移动节点的人,因此您需要更新模拟的nodes和links。
在Mike Bostock的这个例子中:https://bl.ocks.org/mbostock/1095795他更新了restart
函数中的模拟,如下所示:
simulation.nodes(nodes);
simulation.force("link").links(links);
simulation.alpha(1).restart();