d3.js label strategy
by Anonymous
HTML
<!DOCTYPE html>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
JavaScript
var width = 960,
height = 500;
var randomStrLength = Math.floor(Math.random() * 20),
pool = 'abc',
randomStr = '';
var pl = pool.length
for (var i = 0; i < randomStrLength; i++) {
var randomChar = pool.substr(Math.floor(Math.random() * pl), 1);
randomStr += randomChar;
}
var fill = d3.scale.category10();
var nodes = [],
foci = [{x: 150, y: 150}, {x: 350, y: 250}, {x: 700, y: 400}];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.nodes(nodes)
.links([])
.gravity(0)
.size([width, height])
.on("tick", tick);
var node = svg.selectAll("circle");
function tick(e) {
var k = .1 * e.alpha;
// Push nodes toward their designated focus.
nodes.forEach(function(o, i) {
o.y += (foci[o.id].y - o.y) * k;
o.x += (foci[o.id].x - o.x) * k;
});
node
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; });
}
var stopIterations = 100;
var iterations = 0;
setInterval(function(){
if(iterations == stopIterations){
return;
}
nodes.push({id: ~~(Math.random() * foci.length)});
force.start();
node = node.data(nodes);
node.enter().append("rect")
.attr("class", "node")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.attr("width", 100)
.attr("height", 20)
.style("fill", function(d) { return fill(d.id); })
.style("stroke", function(d) { return d3.rgb(fill(d.id)).darker(2); })
.call(force.drag);
iterations++;
}, 5);