D3.js 使用根节点勾选后居中力导向布局(返回居中)

D3.js 使用根节点勾选后居中力导向布局(返回居中),d3.js,force-layout,D3.js,Force Layout,我正在试验使用D3.js的强制导向布局。我需要的是按根(或其他选定节点)将布局居中,并在完成勾选功能后将该节点返回到svg(例如画布)中心(图形alpha较低)。可能吗?我在网站上找到了一个例子 但我无法使根(使用aplha或其他自定义勾号函数计算时)返回到中心(通过此特定节点使布局居中) 如有任何帮助,我们将不胜感激。请尝试更改force事件处理程序,如下所示: force.on("tick", function(e) { nodes[0].x = w / 2; nodes[0].y = h

我正在试验使用D3.js的强制导向布局。我需要的是按根(或其他选定节点)将布局居中,并在完成勾选功能后将该节点返回到svg(例如画布)中心(图形alpha较低)。可能吗?我在网站上找到了一个例子

但我无法使根(使用aplha或其他自定义勾号函数计算时)返回到中心(通过此特定节点使布局居中)


如有任何帮助,我们将不胜感激。

请尝试更改force事件处理程序,如下所示:

force.on("tick", function(e) {
nodes[0].x = w / 2;
nodes[0].y = h / 2;

var k = 0.05 * e.alpha;
          nodes.forEach(function(o, i) {
            o.y += (nodes[0].y - o.y) * k;
            o.x += (nodes[0].x - o.x) * k;
          });

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("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });
 });

实际上,我是这样解决的(类似于之前的,但更复杂):


谢谢你的回复。我已经在使用这个解决方案,问题是所选节点是可拖动的,但在图形稳定后它不会返回到给定的(原始)坐标。我还尝试使用graph tick函数的alpha(heat)值,但两种解决方案都没有效果。我需要允许用户拖动图形,然后通过某个选定节点将图形返回到“固定”位置:-)
force.on("tick", function(e) {

     node.attr("transform", function(d) { 
         //TODO move these constants to the header section
        //center the center (root) node when graph is cooling down
        if(d.index==0){
            damper = 0.1;
            d.x = d.x + (w/2 - d.x) * (damper + 0.71) * e.alpha;
            d.y = d.y + (h/2 - d.y) * (damper + 0.71) * e.alpha;
        }
        //start is initiated when importing nodes from XML
        if(d.start === true){
            d.x = w/2;
            d.y = h/2;
            d.start = false;
        }

        r = d.name.length;
        //these setting are used for bounding box, see [http://blockses.appspot.com/1129492][1]
        d.x = Math.max(r, Math.min(w - r, d.x));
        d.y = Math.max(r, Math.min(h - r, d.y));

            return "translate("+d.x+","+d.y+")";            

     }
    );

     });