简体   繁体   中英

Bounded Static Force Layout in D3js v5

Bounded Static Force Layout - help?

How can we create a bounded static force layout where simulation.tick() is manually called?

In the D3js documentation , we see that the "tick" event isn't dispatched when manually running the sim. Typically a bound could be imposed on the x & y values for each tick event (see this bounded force layout ). Hence, this question is focused on how to have the node's x & y coordinates respect the bounds on each tick of the simulation.

As an example, where could we place bounds on this block so the node's x & y values stay within the red box?

所需的边界框。

Failure #1

I tried to create a bounding box force function. Not sure what's happening here yet.

失败 1

Code

All of the code for these examples is available on Observable .

The problem with your code is not the missing events but the wrong setup up of your simulation's forces. The original example is build using the default values for the positioning forces d3.forceX and d3.forceY which are 0. This centers all calculations around the origin. The whole shebang is centered in the viewport by translating the g element to width/2 and height/2 . Since you commented out the translation this centering is no longer working smushing your nodes to the upper and left border.

This can easily be cured by correctly configuring the positioning forces:

.force("x", d3.forceX(d3.mean(xExtent)))
.force("y", d3.forceY(d3.mean(yExtent)))

This will put the center of the layout to the center of your bounding rectangle.

Although this already works you might want to turn down the repelling force which is too strong forcing most nodes on the outer border. Halfing that value immediately yields visually pleasing results.

.force("charge", d3.forceManyBody().strength(-40))

Here is the updated notebook .

Fil tweaked my failure #1 to create the following solution: 在此处输入图片说明

Code for this solution is on Observable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM