Re-layout D3 layout on node click

I am trying to create a force diagram that gets a click on the center.

I follow this as a base:

enter image description here

I tried to adjust the click function to set d.fixed=true , and also assign fixed points to dx and dy .

However, I need to enable d.fixed=false for all other nodes. In addition, node does not go to the center click.

My question is how to set all other fixed properties to false and then redraw the force diagram with a new center?

I prepared an example here :

enter image description here

The click function is pretty simple:

  function click(d) { d.fixed=true; dx=10; dy=10; update(); } 

I tried adding this to a function:

 root.forEach(function (d) { d.fixed = false; }); 
+6
source share
2 answers

You can access the nodes using force.nodes() and iterate to set the fixed attribute to false .

 force.nodes().forEach(function(d) { d.fixed = false; }); 

and then update the schedule. I deployed your example here and added a double-click listener that restarts the force layout. Yours faithfully,

+6
source

A few things are in order, I approached the problem. Here is the final violin if you want to follow further.

First, your update() method does a lot more than just updating the position of the nodes; he counts the whole tree. This is too complicated for what you are trying to do, and in the end it was not the source of the problem, I still recommend using force.resume() to get the timer mark, and the nodes are moving again.

Secondly, you were on the right track by adding a forEach statement to disable the old fixed nodes. But forEach works with arrays, and root is an object. Therefore, either reuse the flatten method (slow), or do as @Pablo suggested and use force.nodes () to get the nodes as an array (better).

Thirdly, and it was a little thought: if you set w630> as β€œfixed”, the force layout ignores any new dx and dy values, returning them back to d.px and d.py (previous values). (I I suppose this is so that if the node is dragged, it will automatically return to its fixed position.) Therefore, to move it to be fixed where you want, you must set the β€œprevious” values, not the new values. the problem is that this leads to an immediate jump in position, but n If you want to add a transition for this node (so that it looks like it is being dragged to the center) before calling force.resume() .

+4
source

All Articles