script_d3js.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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().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(d.group); })
  24. .attr("id",function(d) { return d.identifiant; })
  25. .attr("href",function(d) { return d.cible; })
  26. .call(d3.drag()
  27. .on("start", dragstarted)
  28. .on("drag", dragged)
  29. .on("end", dragended));
  30. simulation
  31. .nodes(graph.nodes)
  32. .on("tick", ticked);
  33. simulation.force("link")
  34. .links(graph.links);
  35. function ticked() {
  36. link
  37. .attr("x1", function(d) { return d.source.x; })
  38. .attr("y1", function(d) { return d.source.y; })
  39. .attr("x2", function(d) { return d.target.x; })
  40. .attr("y2", function(d) { return d.target.y; });
  41. node
  42. .attr("x", function(d) { return d.x; })
  43. .attr("y", function(d) { return d.y; });
  44. }
  45. });
  46. function dragstarted(d) {
  47. if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  48. d.fx = d.x;
  49. d.fy = d.y;
  50. }
  51. function dragged(d) {
  52. d.fx = d3.event.x;
  53. d.fy = d3.event.y;
  54. }
  55. function dragended(d) {
  56. if (!d3.event.active) simulation.alphaTarget(0);
  57. d.fx = null;
  58. d.fy = null;
  59. }