Skip to content

Instantly share code, notes, and snippets.

@csiu
Last active September 7, 2017 04:40
Show Gist options
  • Save csiu/dd14223d8f081bed690eede4b19cfcc3 to your computer and use it in GitHub Desktop.
Save csiu/dd14223d8f081bed690eede4b19cfcc3 to your computer and use it in GitHub Desktop.
Force-directed stars
<!DOCTYPE html>
<html>
<script src="https://d3js.org/d3.v3.js"></script>
<body></body>
<script>
var w = 960,
h = 500,
nodes = [],
node;
var vis = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var force = d3.layout.force()
.gravity(0.06)
.charge(-40)
.nodes(nodes)
.size([w, h]);
force.on("tick", function(e) {
vis.selectAll("polygon")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
setInterval(function() {
// Define shape size.
nodes.push({
size: Math.random() * 30 + 10
});
// Restart the layout.
force.start();
vis.selectAll("polygon")
.data(nodes)
.enter().append("polygon")
.attr("points", function(d) {
return CalculateStarPoints(-100, 0, 5, d.size, d.size / 2);
})
.call(force.drag);
}, 1000);
function CalculateStarPoints(centerX, centerY, arms, outerRadius, innerRadius) {
var results = "";
var angle = 2 * Math.PI / arms;
var rot = 2 * Math.PI * Math.random();
for (var i = 0; i < 2 * arms; i++) {
var r = (i & 1) == 0 ? outerRadius : innerRadius;
var pointX = centerX + Math.cos(i * angle + rot) * r;
var pointY = centerY + Math.sin(i * angle + rot) * r;
// Our first time we simply append the coordinates, subsequet times
// we append a ", " to distinguish each coordinate pair.
if (i == 0) {
results = pointX + "," + pointY;
} else {
results += ", " + pointX + "," + pointY;
}
}
return results;
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment