d3.js / migration - simple force simulation example from d3.v3 to d3.v7

237 views Asked by At

I would like to run a simple working code with d3.v7 (7.8.5) from a d3.v3 version. I am looking to have the same behaviours, especially drag.

My Graph

Any help welcomed.

The code is available here : https://jsfiddle.net/PBrockmann/mq1etbf0/

var force = d3.layout.force()
           .nodes(data.nodes)
           .links(data.links)
           .size([width, height])
           .linkDistance([50])
           .charge([-100])
           .start();

Here is a try with d3.v7.js : https://jsfiddle.net/PBrockmann/cLnbeujp/

But the drag disappears after one drag.

1

There are 1 answers

0
PBrockmann On

The following jsfiddle has been updated with a working solution : https://jsfiddle.net/PBrockmann/cLnbeujp/

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().distance(50))
  .force("charge", d3.forceManyBody().strength(-100))
  .force("collide", d3.forceCollide())
  .force("x", d3.forceX())
  .force("y", d3.forceY())
  .force("center", d3.forceCenter(width / 2, height / 2));

and

function dragged(event, d) {
  d.fx = event.x;
  d.fy = event.y;
  simulation.alphaTarget(0.3).restart();
}

0.3 for alphaTarget gives close behaviours observed in d3.v3