Skip to content

Instantly share code, notes, and snippets.

@alazyer
Forked from barnabemonnot/caterpillar.js
Last active August 29, 2015 14:15
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 alazyer/978526b6c33baed07888 to your computer and use it in GitHub Desktop.
Save alazyer/978526b6c33baed07888 to your computer and use it in GitHub Desktop.
var vv = window,
w = vv.innerWidth,
h = vv.innerHeight;
var svg = d3.select("#animviz")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g").attr("class", "links");
svg.append("g").attr("class", "nodes");
var nodes = [{id:0}], links = [];
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([w, h])
.linkDistance(50)
.charge(-500)
.on("tick", tick);
var legs = 3;
var colorStep = 3;
var rmax = 30;
var iter = 1;
function addData() {
var n = iter;
iter++;
nodes.push({id: n});
links.push({source: nodes[nodes.map(function(d) { return d.id; }).indexOf(n-((n-1)%legs+1))], target: nodes[nodes.map(function(d) { return d.id; }).indexOf(n)]});
if (n > 360/colorStep && n%legs == 0) {
nodes.splice(0, legs);
links.splice(0, legs);
}
}
var node = svg.select(".nodes").selectAll(".node"),
link = svg.select(".links").selectAll(".link");
function update() {
force.start();
link = link.data(force.links(), function(d) { return d.source.id+"-"+d.target.id; });
link.enter()
.append("line")
.attr("class", "link")
.attr("stroke", "#ccc")
.attr("stroke-width", 2);
link.exit().remove();
var r = d3.scale.sqrt()
.domain(d3.extent(force.nodes(), function(d) {return d.weight; }))
.range([15, rmax]);
node = node.data(force.nodes(), function(d) { return d.id; });
node.enter()
.append("circle")
.attr("class", "node")
// Size of the nodes depend on their weight
node.attr("r", function(d) { return r(d.weight); })
.attr("fill", function(d) {
return "hsl("+(colorStep*d.id)%360+", 83%, 60%)";
})
.call(force.drag);
node.exit().remove();
}
update();
var interval = 0.1;
setInterval(function() {
addData();
update();
}, interval*1000);
function tick() {
link.attr("x1", function(d) {return d.source.x;})
.attr("y1", function(d) {return d.source.y;})
.attr("x2", function(d) {return d.target.x;})
.attr("y2", function(d) {return d.target.y;});
node.attr("cx", function(d) { return d.x = Math.max(rmax, Math.min(w - rmax, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(rmax, Math.min(h - rmax, d.y)); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment