我有一个使用 d3.js 构建的强制布局,节点以 15 秒的间隔进入。当节点进入时,它们会从任意方向进入,然后定居在中心。我希望节点始终从左上(0,0)进入,然后到中心定居。
that.force = d3.layout.force()
.charge(-8.6)
.linkDistance(2)
.size([600, 600]);
that.svg = d3.select(that.selector).append("svg")
.attr("width", that.width)
.attr("height", that.height);
d3.json("data/tweets.json", function(error, graph) {
that.graph = graph;
setInterval(function () {
d3.json("data/tweets.json", function(error, graph) {
that.graph = graph;
that.render();
});
},15000);
that.force
.nodes(that.graph.nodes)
.links(that.graph.links)
.start(0);
that.nodes = that.svg.selectAll("g")
.data(that.graph.nodes)
.enter()
.append("g")
.call(that.force.drag);
that.nodes
.append("rect")
.attr("class", "node")
.attr("width", that.rectw)
.attr("height", that.recth)
.style("fill","white")
.style("stroke", function(d) { return d.COLOR; })
.style("stroke-width", "1px")
that.nodes.append("title")
.text(function(d) { return d.SCREEN_NAME; });
that.nodes.append("image")
.attr("class", "node-image")
.attr("transform", "translate(1,1)")
.attr("xlink:href", function(d) { return "img/"+d.PROFILE_PIC;})
.attr("height", that.rectw-2 + "px")
.attr("width", that.recth-2 + "px");
that.link = that.svg.selectAll(".link")
.data(that.graph.links)
.enter()
.append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
that.force.on("tick", function() {
that.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; });
that.nodes.attr("transform", function(d) {
return "translate("+d.x+","+d.y+")";
})
});
});
任何建议都会有帮助。
谢谢。
最佳答案
您可以通过设置数据的 x
和 y
属性,在将节点赋予强制布局之前预先设置节点的位置。因此,在您的情况下,您所需要做的就是将所有节点的 x
和 y
初始化为 0。
关于javascript - 设置强制布局中节点的入口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23809051/