首先如果你想在某个时间“冻结”图形,可以使用force布局的stop命令:
force.stop()
一个很好的用途是首先让图形自组织(使用tick)然后停止强制:
// include in beginning of script
force.start();
for (var i = 0; i < n; ++i) force.tick();
force.stop();
然后,如果您想拖放节点,一个好主意是在 d3 示例页面上搜索 drag,您会找到以下链接:Drag and Drop Support to set nodes to fixed position when dropped,其中包含您想要的一切。顺便说一句,它也与你可能会感兴趣的一个 stackoverflow 问题有关:D3 force directed graph with drag and drop support to make selected node position fixed when dropped
这是用于拖放的有趣代码,适用于力已停止的图形(我只是注释了一些行,但不确定,因此请通过取消注释来验证它是否按预期工作)
var node_drag = d3.behavior.drag()
.on("dragstart", dragstart)
.on("drag", dragmove)
.on("dragend", dragend);
function dragstart(d, i) {
//force.stop() // stops the force auto positioning before you start dragging
}
function dragmove(d, i) {
d.px += d3.event.dx;
d.py += d3.event.dy;
d.x += d3.event.dx;
d.y += d3.event.dy;
tick(); // this is the key to make it work together with updating both px,py,x,y on d !
}
function dragend(d, i) {
//d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
//tick();
//force.resume();
}
function tick() {
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 + ")"; });
};