JSFiddle - React, Tailwind, and code Playground
by Shawn Allen
HTML
<!DOCTYPE html>
<html>
<head>
<title>Force-Directed Layout</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
</body>
</html>
CSS
circle {
stroke-width: 1.5px;
}
line {
stroke: #999;
}
JavaScript
var w = 960,
h = 500,
r = 6,
dist = 50,
fill = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(dist)
.size([w, h]);
var svg = d3.select("body")
.append("svg:svg")
.attr("width", w)
.attr("height", h);
d3.json("http://bl.ocks.org/d/1129492/readme.json", function(json) {
var link = svg.selectAll("line").data(json.links).enter().append("svg:line");
var node = svg.selectAll("circle")
.data(json.nodes)
.enter()
.append("svg:circle")
.attr("r", r - .75)
.style("fill", function(d) {
return fill(d.group);
})
.style("stroke", function(d) {
return d3.rgb(fill(d.group)).darker();
})
.call(force.drag)
.on("mouseover", function(d) {
d.fixed = true;
d3.select(this).attr("r", r * 2);
force.stop();
force.linkDistance(function(link) {
var len = isConnected(d, link.source) || isConnected(d, link.target)
? dist * 2
: dist * 1.25;
return len;
});
force.start();
})
.on("mouseout", function(d) {
d.fixed = false;
d3.select(this).attr("r", r - .75);
force.stop();
force.linkDistance(dist);
force.start();
});
force.nodes(json.nodes)
.links(json.links)
.on("tick", tick)
.start();
var linkedByIndex = {};
json.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index;
}
function tick() {
node.attr("cx", function(d) {
...