Creating forces

Let's create a centering force at the center of screen, which will pull all of the elements toward it. Adjust the code that we added in the previous step, so that it looks as follows. Not that we only add .force("center_force", d3.forceCenter(WIDTH / 2, HEIGHT / 2)) to the previous code:

d3.forceSimulation()
    .nodes(nodesData)    // add the line below this comment
    .force("center_force", d3.forceCenter(WIDTH / 2, HEIGHT / 2))             .on("tick", function(){
        nodes.attr("cx", function(datum) {return datum.x;})
            .attr("cy", function(datum) {return datum.y;});

        links.attr("x1", function(datum) {return datum.source.x;})
            .attr("y1", function(datum) {return datum.source.y;})
            .attr("x2", function(datum) {return datum.target.x;})
            .attr("y2", function ...

Get D3.js Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.