This example uses d3.forceCollide to prevent circles from overlapping.
Last active
August 3, 2020 19:33
-
-
Save mbostock/31ce330646fa8bcb7289ff3b97aab3f5 to your computer and use it in GitHub Desktop.
Collision Detection
This file contains hidden or 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 | |
height: 960 |
This file contains hidden or 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> | |
<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(function(d) { return d.r + 0.5; }).iterations(2)) | |
.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) { | |
context.moveTo(d.x + d.r, d.y); | |
context.arc(d.x, d.y, d.r, 0, tau); | |
}); | |
context.fillStyle = "#ddd"; | |
context.fill(); | |
context.strokeStyle = "#333"; | |
context.stroke(); | |
context.restore(); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you provide an example of this where you use an SVG object rather than a canvas?