Last active
July 9, 2017 19:25
-
-
Save mbostock/a4b53ef57fce8fffc423 to your computer and use it in GitHub Desktop.
N-Body Problem II
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 | |
height: 960 |
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> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
background: #000; | |
} | |
</style> | |
<canvas width="960" height="960"></canvas> | |
<script src="//d3js.org/d3.v4.0.0-alpha.33.min.js"></script> | |
<script> | |
var canvas = document.querySelector("canvas"), | |
context = canvas.getContext("2d"), | |
width = canvas.width, | |
height = canvas.height; | |
var n = 400, | |
pi = Math.PI, | |
tau = 2 * pi; | |
var nodes = d3.range(n).map(function() { | |
var r = Math.random() * width / 3, | |
a = Math.random() * tau, | |
x = width / 2 + r * Math.cos(a), | |
y = height / 2 + r * Math.sin(a); | |
return { | |
x: x, | |
y: y, | |
vx: (height / 2 - y) * 0.006, | |
vy: (x - width / 2) * 0.006 | |
}; | |
}); | |
var force = d3.forceSimulation(nodes) | |
.drag(0) | |
.alphaDecay(0) | |
.force("charge", d3.forceManyBody().strength(0.02)) | |
.force("center", d3.forceCenter(width / 2, height / 2)) | |
.on("tick", ticked); | |
var stroke = d3.scaleLinear() | |
.domain([0, 10]) | |
.range(["magenta", "yellow"]); | |
function ticked() { | |
context.clearRect(0, 0, width, height); | |
context.lineWidth = 4; | |
context.lineCap = "square"; | |
for (var i = 0, node, vx, vy; i < n; ++i) { | |
node = nodes[i]; | |
context.beginPath(); | |
context.moveTo(node.x, node.y); | |
context.lineTo(node.x + node.vx * 3, node.y + node.vy * 3); | |
context.strokeStyle = stroke(node.vx * node.vx + node.vy * node.vy); | |
context.stroke(); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment