Skip to content

Instantly share code, notes, and snippets.

@steveharoz
Forked from mbostock/.block
Last active October 11, 2016 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveharoz/3fc45e398b8bd7a17460698e79c19d03 to your computer and use it in GitHub Desktop.
Save steveharoz/3fc45e398b8bd7a17460698e79c19d03 to your computer and use it in GitHub Desktop.
Collision Detection
license: gpl-3.0
height: 960

Test if d3.forceCollide can reinitialize after updating the node radii

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="960"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
tau = 2 * Math.PI;
var nodes = d3.range(1000).map(function(i) {
return {
r: Math.random() * 14 + 4
};
});
var simulation = d3.forceSimulation(nodes)
.velocityDecay(0.2)
.force("x", d3.forceX().strength(0.002))
.force("y", d3.forceY().strength(0.002))
.force("collide", d3.forceCollide().radius(d => d.r + 0.5).iterations(5))
.on("tick", ticked);
function ticked() {
context.clearRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2);
context.beginPath();
nodes.forEach(function(d) {
var newR = d.r * (1+iteration/2);
context.moveTo(d.x + newR, d.y);
context.arc(d.x, d.y, newR, 0, tau);
});
context.fillStyle = "#ddd";
context.fill();
context.strokeStyle = "#333";
context.stroke();
context.restore();
}
var iteration = false;
setInterval(() => {
iteration = !iteration;
simulation.force("collide").radius(d => d.r * (1+iteration/2));
simulation.alpha(1).restart();
}, 2000);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment