d3 v4 force

by bejnar

HTML

<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-transition.v1.min.js"></script>
<svg width="500" height="500"></svg>

CSS

.link {
  stroke: #aaa;
}

.node {
  pointer-events: all;
  stroke: none;
  stroke-width: 40px;
}

#1 {
  border: 9px solid blue;
}

JavaScript

var t = d3.transition()
    .duration(2500)
    .ease(d3.easeLinear);


var nodes = [
  {"id": 1, "name": "F", "fx": 200, "fy": 200, "static": true},
  {"id": 2, "name": "F", "fx": 250, "fy": 250, "static": true},
  {"id": 3, "name": "F", "fx": 300, "fy": 250, "static": true},
  {"id": 4, "name": "4", "static": false},
  {"id": 5, "name": "5", "static": false},
  {"id": 6, "name": "6", "static": false},
  {"id": 7, "name": "7", "static": false},
  {"id": 8, "name": "8", "static": false},
  {"id": 9, "name": "9", "static": false}
]

var links = [
  {source: 1, target: 2},
  {source: 1, target: 3},
  {source: 1, target: 4},
  {source: 2, target: 5},
  {source: 2, target: 6},
  {source: 3, target: 7},
  {source: 5, target: 8},
  {source: 6, target: 9},
  {source: 9, target: 1},
  {source: 9, target: 2},
  {source: 9, target: 3},
]

var index = 10;
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height"),
    node,
    link;

var simulation = d3.forceSimulation(nodes)
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));


function update() {
  link = svg.selectAll(".link")
    .data(links, function(d) { return d.target.id; })

  link = link.enter()
    .append("line")
    .attr("class", "link");

  node = svg.selectAll(".node")
    .data(nodes, function(d) { return d.id; })

  node = node.enter()
    .append("g")
    .attr("class", "node")
    .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended)); 

  node.append("circle")
    .attr("r", 2.5)

  node.append("title")
      .text(function(d) { return d.id; });

  node.append("text")
      .attr("dy", 3)
      .text(function(d) { return d.name; });

  simulation
      .nodes(nodes)
      .on("tick", ticked);

  simulation.force("link")
      .links(links);
}

function ticked() {
  link
      .attr("x1", function(d)...