Built with blockbuilder.org
forked from plmrry's block: Collision Radius Transition
license: gpl-3.0 |
Built with blockbuilder.org
forked from plmrry's block: Collision Radius Transition
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<script> | |
var width = 400; | |
var height = 400; | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
var data = d3.range(100).map(function() { | |
return { radius: Math.random() * 20 } | |
}); | |
var forceCollide = d3.forceCollide(function(d) { return d.radius; }) | |
.strength(0.8); | |
var s = 0.05 | |
var forceX = d3.forceX(width/2).strength(s); | |
var forceY = d3.forceY(height/2).strength(s); | |
var force = d3.forceSimulation(data) | |
.force('x', forceX) | |
.force('y', forceY) | |
.force('center', d3.forceCenter(width/2, height/2)) | |
.force('collide', forceCollide) | |
.on('tick', function() { | |
svg.selectAll('.node') | |
.attr('cx', function(d) { return d.x; }) | |
.attr('cy', function(d) { return d.y; }) | |
}) | |
svg.selectAll('.node') | |
.data(data) | |
.enter() | |
.append('circle') | |
.classed('node', true) | |
.style('opacity', 0.5) | |
.attr('r', function(d) { return d.radius; }); | |
force.nodes(data) | |
.alpha(1) | |
.restart() | |
d3.select(svg.node().parentNode).append('button').text('grow') | |
.on('click', switchRadius(100)) | |
d3.select(svg.node().parentNode).append('button').text('shrink') | |
.on('click', switchRadius(10)) | |
function switchRadius(newRadius) { | |
return function() { | |
d3.selectAll('.node') | |
.filter(function(d,i) { return i === 5; }) | |
.transition().duration(1000) | |
.tween('radius', function(d) { | |
var that = d3.select(this); | |
var i = d3.interpolate(d.radius, newRadius); | |
return function(t) { | |
d.radius = i(t); | |
that.attr('r', function(d) { return d.radius; }); | |
force.nodes(data) | |
} | |
}); | |
force.alpha(1).restart(); | |
} | |
} | |
</script> | |
</body> |