Guest User

Untitled

a guest
Dec 10th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <body>
  4. <script src="//d3js.org/d3.v3.min.js"></script>
  5. <script>
  6.  
  7. var width = 960,
  8. height = 500;
  9.  
  10. var nodes = d3.range(200).map(function() { return {radius: Math.random() * 12 + 4}; }),
  11. root = nodes[0],
  12. color = d3.scale.category10();
  13.  
  14. root.radius = 0;
  15. root.fixed = true;
  16.  
  17. var force = d3.layout.force()
  18. .gravity(0.05)
  19. .charge(function(d, i) { return i ? 0 : -2000; })
  20. .nodes(nodes)
  21. .size([width, height]);
  22.  
  23. force.start();
  24.  
  25. var svg = d3.select("body").append("svg")
  26. .attr("width", width)
  27. .attr("height", height);
  28.  
  29. svg.selectAll("circle")
  30. .data(nodes.slice(1))
  31. .enter().append("circle")
  32. .attr("r", function(d) { return d.radius; })
  33. .style("fill", function(d, i) { return color(i % 3); });
  34.  
  35. force.on("tick", function(e) {
  36. var q = d3.geom.quadtree(nodes),
  37. i = 0,
  38. n = nodes.length;
  39.  
  40. while (++i < n) q.visit(collide(nodes[i]));
  41.  
  42. svg.selectAll("circle")
  43. .attr("cx", function(d) { return d.x; })
  44. .attr("cy", function(d) { return d.y; });
  45. });
  46.  
  47. svg.on("mousemove", function() {
  48. var p1 = d3.mouse(this);
  49. root.px = p1[0];
  50. root.py = p1[1];
  51. force.resume();
  52. });
  53.  
  54. function collide(node) {
  55. var r = node.radius + 16,
  56. nx1 = node.x - r,
  57. nx2 = node.x + r,
  58. ny1 = node.y - r,
  59. ny2 = node.y + r;
  60. return function(quad, x1, y1, x2, y2) {
  61. if (quad.point && (quad.point !== node)) {
  62. var x = node.x - quad.point.x,
  63. y = node.y - quad.point.y,
  64. l = Math.sqrt(x * x + y * y),
  65. r = node.radius + quad.point.radius;
  66. if (l < r) {
  67. l = (l - r) / l * .5;
  68. node.x -= x *= l;
  69. node.y -= y *= l;
  70. quad.point.x += x;
  71. quad.point.y += y;
  72. }
  73. }
  74. return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
  75. };
  76. }
  77.  
  78. </script>
Add Comment
Please, Sign In to add comment