JSFiddle - React, Tailwind, and code Playground
CSS
.link {
stroke: #000;
stroke-width: 1.5px;
}
.node {
cursor: move;
fill: #ccc;
stroke: #000;
stroke-width: 1.5px;
}
JavaScript
var graph = {
"nodes": [
{id: 0},
{id: 1},
{id: 2},
{id: 3}
],
"links": [
{"source": 0, "target": 1},
{"source": 1, "target": 2},
{"source": 2, "target": 0},
{"source": 1, "target": 3},
{"source": 3, "target": 2}
],
"time": [
{"source": 1, "time": 1},
{"source": 2, "time": 2.5},
{"source": 3, "time": 2},
{"source": 4, "time": 0.5}
]
}
var width = 400,
height = 400;
var force = d3.layout.force()
.size([width, height])
.charge(-400)
.linkDistance(40)
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
link = svg.selectAll(".link");
node = svg.selectAll(".node");
var i = 0;
function redraw() {
if (i === graph.time.length) return;
setTimeout(function() {
var nodes = graph.nodes.slice(0, i + 1);
var links = graph.links.filter(
function(link) {
return (link.source <= i && link.target <= i)
}
);
draw(nodes, links);
i += 1;
redraw();
}, graph.time[i].time * 1000);
}
redraw();
function draw(nodes, links) {
force
.nodes(nodes)
.links(links)
.start();
link.data(links, function(d) {return d.source.id + "-" + d.target.id;})
.enter().append("line")
.attr("class", "link");
node.data(nodes, function(d) {return d.id;})
.enter().append("circle")
.attr("class", "node")
.attr("r", 12)
.call(force.drag());
link = svg.selectAll(".link");
node = svg.selectAll(".node");
}
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}