Modifying a radius with collision detection.
Last active
May 17, 2017 14:15
-
-
Save plmrry/b9db6d47dabaff6e59f565d9287c4064 to your computer and use it in GitHub Desktop.
Collision Radius Transition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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.02; | |
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment