script_d3js.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. var svg = d3.select("#links svg"),
  2. width = +svg.attr("width"),
  3. height = +svg.attr("height");
  4. var color = d3.scaleOrdinal(d3.schemeCategory20);
  5. var simulation = d3.forceSimulation()
  6. .force("link", d3.forceLink(10).distance(50).id(function(d) { return d.id; }))
  7. .force("charge", d3.forceManyBody())
  8. .force("center", d3.forceCenter(width / 2, height / 2));
  9. d3.json("user/themes/r2c/json/miserables.json", function(error, graph) {
  10. if (error) throw error;
  11. var link = svg.append("g")
  12. .attr("class", "links")
  13. .selectAll("line")
  14. .data(graph.links)
  15. .enter().append("line")
  16. .attr("stroke-width", function(d) { return Math.sqrt(d.value); });
  17. var node = svg.append("g")
  18. .attr("class", "nodes")
  19. .selectAll("text")
  20. .data(graph.nodes)
  21. .enter().append("text")
  22. .text(function(d) { return d.id; })
  23. // .attr("fill", function(d) { return color(); })
  24. .attr("class",function(d) { return "group" + d.group ;})
  25. .attr("id",function(d) { return d.identifiant; })
  26. .attr("href",function(d) { return d.cible; })
  27. .call(d3.drag()
  28. .on("start", dragstarted)
  29. .on("drag", dragged)
  30. .on("end", dragended));
  31. simulation
  32. .nodes(graph.nodes)
  33. .on("tick", ticked);
  34. simulation.force("link")
  35. .links(graph.links);
  36. function ticked() {
  37. link
  38. .attr("x1", function(d) { return d.source.x; })
  39. .attr("y1", function(d) { return d.source.y; })
  40. .attr("x2", function(d) { return d.target.x; })
  41. .attr("y2", function(d) { return d.target.y; });
  42. node
  43. .attr("x", function(d) { return d.x; })
  44. .attr("y", function(d) { return d.y; });
  45. }
  46. });
  47. function dragstarted(d) {
  48. if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  49. d.fx = d.x;
  50. d.fy = d.y;
  51. }
  52. function dragged(d) {
  53. d.fx = d3.event.x;
  54. d.fy = d3.event.y;
  55. }
  56. function dragended(d) {
  57. if (!d3.event.active) simulation.alphaTarget(0);
  58. d.fx = null;
  59. d.fy = null;
  60. }