Skip to content

Instantly share code, notes, and snippets.

@emilbayes
Forked from mbostock/.block
Last active February 22, 2016 12:28
Show Gist options
  • Save emilbayes/4e82e66e72afffddca78 to your computer and use it in GitHub Desktop.
Save emilbayes/4e82e66e72afffddca78 to your computer and use it in GitHub Desktop.
N-Body Problem
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
background: #000;
}
</style>
<canvas width="960" height="500"></canvas>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var centerXScale = d3.scale.linear().range([-width/3, width/3])
var centerYScale = d3.scale.linear().range([-height/3, height/3])
var n = 200,
tau = 2 * Math.PI,
nodes = d3.range(n).map(function() { return {radius: Math.random() * 8 + 2}; })
.concat(d3.range(30).map(function () {
var x = centerXScale(Math.random())
var y = centerYScale(Math.random())
var angle = (Math.atan2(y, x) - 0.01 + tau) % tau
return {
radius: Math.random() * 8 + 2,
x,
y,
px: x * Math.cos(angle),
py: y * Math.sin(angle)
}
}));
var force = d3.layout.force()
.charge(0.5)
.gravity(0.1)
.friction(1)
.nodes(nodes)
.size([width, height])
.start();
var stroke = d3.scale.linear()
.domain([0, 1])
.range(["steelblue", "brown"]);
force.on("tick", function(e) {
var q = d3.geom.quadtree(nodes), node, i, vx, vy;
context.clearRect(0, 0, width, height);
context.lineWidth = 1.5;
for (i = 0; i < n; ++i) {
q.visit(collide(nodes[i]));
}
for (i = 0; i < n; ++i) {
node = nodes[i];
context.beginPath();
context.arc(node.x, node.y, node.radius - 0.75, 0, tau);
context.strokeStyle = stroke((vx = node.x - node.px) * vx + (vy = node.y - node.py) * vy);
context.stroke();
}
context.beginPath();
for (i = 0; i < n; ++i) {
node = nodes[i];
context.moveTo(node.x, node.y);
context.lineTo(node.x + (node.x - node.px) * 3, node.y + (node.y - node.py) * 3);
}
context.strokeStyle = "#fff";
context.stroke();
force.resume();
});
function collide(node) {
var r = node.radius + 16,
nx1 = node.x - r,
nx2 = node.x + r,
ny1 = node.y - r,
ny2 = node.y + r;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = node.radius + quad.point.radius;
if (l < r) {
l = (l - r) / (l * 2);
node.x -= x *= l;
node.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment