JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://raw.github.com/mbostock/d3/master/d3.v2.min.js"></script>
<button id="resize">Resize</button>
<button id="random">Randomify data</button><br />
<svg id="container" width=600 height=400 style="border: 1px solid black;">
</svg>
JavaScript
var nodes;
makeSomeNodes();
var svg = $('svg');
var layout = d3.layout.force()
.links([])
.on('tick', update);
var width,height;
restart();
function restart() {
width = svg.width();
height= svg.height();
var nodeElements = d3.select('svg')
.selectAll('circle')
.data(nodes);
nodeElements
.enter().append('circle')
.attr('r', 5)
.attr('fill', 'blue');
nodeElements.exit().remove();
var numNodesAcrossRadius = Math.sqrt(nodes.length / 3.14159);
var charge = Math.min(width, height) / numNodesAcrossRadius;
layout
.nodes(nodes)
.charge(-charge)
.size([width , height])
.start();
}
function update() {
d3.select('svg').selectAll('circle')
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
function makeSomeNodes() {
var numNodes = 5+parseInt(Math.random() * 50);
if (!nodes) nodes = [];
nodes = nodes.slice(0, numNodes);
for (var i=nodes.length; i < numNodes; i++) {
nodes[i] = {index: i };
}
console.log(nodes.map(function(n) { return n.index; }));
}
$('#resize').click(function() {
svg.width(width > 200 ? width - 200 : 800);
svg.height(height > 150? height- 150: 600);
restart();
return false;
});
$('#random').click(function() {
makeSomeNodes();
restart();
return false ;
});