Force layout (with collision detection).
From D3 in Depth book by Peter Cook.
license: gpl-3.0 | |
height: 420 | |
border: no |
Force layout (with collision detection).
From D3 in Depth book by Peter Cook.
<!-- <!DOCTYPE html> --> | |
<meta charset="utf-8"> | |
<head> | |
<title>Force layout (with collision detection)</title> | |
</head> | |
<style> | |
circle { | |
fill: orange; | |
} | |
</style> | |
<body> | |
<div id="content"> | |
<svg width="400" height="400"> | |
</svg> | |
</div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.js"></script> | |
<script> | |
var width = 400, height = 400 | |
var numNodes = 100 | |
var nodes = d3.range(numNodes).map(function(d) { | |
return {radius: Math.random() * 25} | |
}) | |
var simulation = d3.forceSimulation(nodes) | |
.force('center', d3.forceX(200)) | |
.force('center', d3.forceY(200)) | |
.force('collision', d3.forceCollide().radius(function(d) { | |
return d.radius | |
})) | |
.on('tick', ticked); | |
function ticked() { | |
var u = d3.select('svg') | |
.selectAll('circle') | |
.data(nodes) | |
u.enter() | |
.append('circle') | |
.attr('r', function(d) { | |
return d.radius | |
}) | |
.merge(u) | |
.attr('cx', function(d) { | |
return d.x | |
}) | |
.attr('cy', function(d) { | |
return d.y | |
}) | |
u.exit().remove() | |
} | |
</script> | |
</body> | |
</html> |