D3 build nodes always start in the upper left corner of the screen

I have a force layout with nodes defined as follows ...

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
        };
    });     

And then the force composition is created later in the code with ...

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

force.nodes(nodes)
      .start();

The reason I forced the values ​​x / y, px / py, cx / cy is because I am just trying to ensure that the nodes do not always start in the upper left corner of the browser (which is only for a split second until the force simulation will affect, but quite noticeably, especially on firefox or mobile devices).

What is strange to me is that I begin to compose the force with my values ​​x / y, cx / cy, px / py BEFORE the code I wrote, connecting the circles, images, etc. that the browser should display - in another word, this code appears AFTER defining / starting the layout of the force ...

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

, , , , -, 0,0. !

+4
2

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;
}
+4

, tick(). , call tick() . node :

nodeEnter.style("visibility", "hidden")

, tick():

nodeEnter.style("visibility", "visible")
+1

Source: https://habr.com/ru/post/1612468/


All Articles