d3强制布局节点始终从屏幕的左上角开始

d3w*_*abe 5 d3.js

我有一个强制布局,节点定义如下......

nodes = someData.map(function (d) {
        return {
            image_location: d.image_location, 
            image_width: d.image_width, 
            image_height: d.image_height, 
            aspect_ratio: d.aspect_ratio,
            radius: circleRadiusScale(d.someCount),
            x: width/2,
            y: height / 2,
            px: width/2,
            py: height/2,
            cx: width/2,
            cy: height / 2
        };
    });     
Run Code Online (Sandbox Code Playgroud)

然后在代码中稍后创建强制布局...

force = d3.layout.force()
    .gravity(.05)
    .alpha(0.1) 
    .size([width, height])
    .on("tick", tick); 

force.nodes(nodes)
      .start();
Run Code Online (Sandbox Code Playgroud)

我强制x/y,px/py,cx/cy值的原因是我只是想确保节点不总是开始被投射到浏览器的左上角(这只是为了一瞬间,直到力模拟生效,但特别是在Firefox或移动设备上非常明显).

对我来说很奇怪的是,我正在用我的x/y,cx/cy,px/py值开始强制布局,然后在我编写的代码中加入浏览器应该显示的圆圈,图像等 - 换句话说,这个代码来自定义/启动力布局后......

node = svg.selectAll(".node")
              .data(force.nodes(), function(d) { return d.id; })
              .enter()           
              .append("g")
              .attr("class", "node") etc to append circles, images...
Run Code Online (Sandbox Code Playgroud)

所以,我想知道如何通过浏览器忍住节点的投影,直到我知道力布局具有比0,0以外的东西的初始位置.谢谢你的任何想法!

Lar*_*off 5

我会检查tick处理程序函数中的位置,并在满足条件后进行初始化:

var initialized = false;
force.on("tick", function() {
  if(!initialized) {
    // can also check multiple nodes here...
    if(nodes[0].x != width/2 && nodes[0].y != height/2) initialize();
  } else {
    // update node positions
  }
});

function initialize() {
  node = svg.selectAll(".node")
          .data(force.nodes(), function(d) { return d.id; })
          .enter()           
          .append("g")
          .attr("class", "node") // etc
  initialized = true;
}
Run Code Online (Sandbox Code Playgroud)