Built with blockbuilder.org
Last active
December 9, 2018 18:23
-
-
Save max-l/74c12cf2228b87d91c4c11a4f40dc8e7 to your computer and use it in GitHub Desktop.
gravity experiments
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: mit |
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"> | |
<title>Clustered Force Layout</title> | |
<body> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500, | |
maxRadius = 12; | |
var n = 100, // total number of circles | |
m = 1; // number of distinct clusters | |
var color = d3.scaleOrdinal(d3.schemeCategory10).domain(d3.range(m)); | |
// The largest node for each cluster. | |
var clusters = new Array(m); | |
var gravityCenter = null | |
var nodes = d3.range(n).map(() => { | |
var i = Math.floor(Math.random() * m), | |
r = Math.sqrt((i + 1) / m * -Math.log(Math.random())) * maxRadius, | |
d = {cluster: i, radius: 8}; | |
gravityCenter = d; | |
return d; | |
}); | |
var forceCollide = d3.forceCollide() | |
.radius(function(d) { return d.radius + 1.5; }) | |
.iterations(1); | |
var force = d3.forceSimulation() | |
.nodes(nodes) | |
.force("center", d3.forceCenter()) | |
.force("collide", forceCollide) | |
.force("cluster", forceCluster) | |
.force("gravity", d3.forceManyBody(80)) | |
.force("x", d3.forceX().strength(.7)) | |
.force("y", d3.forceY().strength(.7)) | |
.on("tick", tick); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.append('g') | |
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')'); | |
var circle = svg.selectAll("circle") | |
.data(nodes) | |
.enter().append("circle") | |
.attr("r", function(d) { return d.radius; }) | |
.style("fill", function(d) { return color(d.cluster); }) | |
// TODO: Update for v4 | |
// .call(force.drag); | |
function tick() { | |
circle | |
.attr("cx", function(d) { return d.x; }) | |
.attr("cy", function(d) { return d.y; }); | |
} | |
function forceCluster(alpha) { | |
for (var i = 0, n = nodes.length, k = alpha * 1; i < n; ++i) { | |
const node = nodes[i]; | |
node.vx -= (node.x - gravityCenter.x) * k; | |
node.vy -= (node.y - gravityCenter.y) * k; | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment