| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Force-Directed Layout (Multiple Foci)</title> | |
| <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script> | |
| <script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js"></script> | |
| <script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js"></script> | |
| </head> | |
| <body> | |
| <script type="text/javascript"> | |
| var w = 960, | |
| h = 500, | |
| fill = d3.scale.category10(), | |
| nodes = [], | |
| foci = [{x: 150, y: 150}, {x: 350, y: 250}, {x: 700, y: 400}]; | |
| var vis = d3.select("body").append("svg:svg") | |
| .attr("width", w) | |
| .attr("height", h); | |
| var force = d3.layout.force() | |
| .nodes(nodes) | |
| .links([]) | |
| .gravity(0) | |
| .size([w, h]); | |
| force.on("tick", function(e) { | |
| // Push nodes toward their designated focus. | |
| var k = .1 * e.alpha; | |
| nodes.forEach(function(o, i) { | |
| o.y += (foci[o.id].y - o.y) * k; | |
| o.x += (foci[o.id].x - o.x) * k; | |
| }); | |
| vis.selectAll("circle.node") | |
| .attr("cx", function(d) { return d.x; }) | |
| .attr("cy", function(d) { return d.y; }); | |
| }); | |
| setInterval(function(){ | |
| nodes.push({id: ~~(Math.random() * foci.length)}); | |
| force.start(); | |
| vis.selectAll("circle.node") | |
| .data(nodes) | |
| .enter().append("svg:circle") | |
| .attr("class", "node") | |
| .attr("cx", function(d) { return d.x; }) | |
| .attr("cy", function(d) { return d.y; }) | |
| .attr("r", 8) | |
| .style("fill", function(d) { return fill(d.id); }) | |
| .style("stroke", function(d) { return d3.rgb(fill(d.id)).darker(2); }) | |
| .style("stroke-width", 1.5) | |
| .call(force.drag); | |
| }, 1000); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment