Accepted answer

You don't want d3.forceCenter. If you look at the API:

The centering force translates nodes uniformly so that the mean position of all nodes (the center of mass if all nodes have equal weight) is at the given position ⟨x,y⟩

This means that, when you move a node away from the center, the other nodes will move in the opposite direction, to compensate the movement, so the center of mass stays at the same position.

Instead, use forceX and forceY:

The x- and y-positioning forces push nodes towards a desired position along the given dimension with a configurable strength.

So, this is the simulation:

const simulation = d3.forceSimulation()
     .force('link', d3.forceLink().distance(200))
     .force('charge', d3.forceManyBody())
     .force('centerX', d3.forceX(width / 2))
     .force('centerY', d3.forceY(height / 2));

Here is an updated fiddle:

Related Query

More Query from same tag