Skip to content

Instantly share code, notes, and snippets.

@ghing
Last active October 3, 2015 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghing/2505876 to your computer and use it in GitHub Desktop.
Save ghing/2505876 to your computer and use it in GitHub Desktop.
Drawing a spider web with d3
<html>
<head>
<title>Webmaking</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://d3js.org/d3.v2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function getPoints(radius, segments, levels) {
points = {
all: [],
byLevel: [],
bySegment: [],
};
for (i = 0; i < levels; i++) {
r = (radius/levels) * (i + 1);
points.byLevel[i] = []
for (j = 0; j < segments; j++) {
if (points.bySegment[j] == undefined) {
points.bySegment[j] = [];
}
theta = ((2 * Math.PI) / segments) * j;
point = {
r: r,
theta: theta,
x: r * Math.cos(theta),
y: r * Math.sin(theta),
level: i
};
points.all.push(point);
points.byLevel[i].push(point);
points.bySegment[j].push(point);
}
}
return points;
}
var svg = d3.select('#web').append('svg').style('width', '100%').style('height', '100%'),
vis = svg.append('g'),
width = 500,
segments = 8,
levels = 4,
points = getPoints(width / 2, segments, levels);
vis.attr("transform", "translate(" + $(window).width() / 2 + ", " + $(window).height() / 2 + ")");
vis.selectAll("circle")
.data(points.all)
.enter().append("circle")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("r", 5)
.attr("class", function(d) {
return "level-" + d.level;
});
for (level = 0; level < levels; level++) {
for (j = 0; j < segments; j++) {
var point = points.byLevel[level][j]
var nextIdx = j + 1 < segments ? j + 1 : 0;
var nextPoint = points.byLevel[level][nextIdx];
vis.append("path")
.attr("d", "M " + point.x + " " + point.y + " L " + nextPoint.x + " " + nextPoint.y)
.style("stroke", "#000");
}
}
for (segment = 0; segment < segments; segment++) {
console.debug(points.bySegment[segment]);
var start = points.bySegment[segment][0];
var end = points.bySegment[segment][levels - 1];
vis.append("path")
.attr("d", "M " + start.x + " " + start.y + " L " + end.x + " " + end.y)
.style("stroke", "#000");
}
});
</script>
</head>
<body>
<div id="web"></div>
</body>
</html>
@biovisualize
Copy link

Could you please fix the broken link to d3.js, using http://d3js.org/d3.v2.min.js ? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment