chartByD3v1.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <template>
  2. <div class="app-container" ref="svgContainer"></div>
  3. </template>
  4. <script>
  5. import * as d3 from 'd3';
  6. export default {
  7. mounted() {
  8. const svgContainer = this.$refs.svgContainer;
  9. const width = svgContainer.clientWidth;
  10. const height = svgContainer.clientHeight;
  11. const links = [
  12. { source: "A", target: "B", value: 1 },
  13. { source: "A", target: "C", value: 2 },
  14. { source: "B", target: "C", value: 3 },
  15. { source: "B", target: "D", value: 4 },
  16. { source: "C", target: "D", value: 5 },
  17. ];
  18. const nodes = [
  19. { id: "A", x: 100, y: 100 },
  20. { id: "B", x: 200, y: 100 },
  21. { id: "C", x: 150, y: 200 },
  22. { id: "D", x: 250, y: 200 },
  23. ];
  24. const svg = d3.select(svgContainer).append("svg")
  25. .attr("width", width)
  26. .attr("height", height);
  27. const link = svg.selectAll("line")
  28. .data(links)
  29. .join("line")
  30. .attr("stroke", "black")
  31. .attr("stroke-width", d => d.value);
  32. const node = svg.selectAll("circle")
  33. .data(nodes)
  34. .join("circle")
  35. .attr("r", 20)
  36. .attr("fill", "red")
  37. .call(drag(simulation));
  38. const label = svg.selectAll("text")
  39. .data(nodes)
  40. .join("text")
  41. .text(d => d.id)
  42. .attr("x", d => d.x)
  43. .attr("y", d => d.y);
  44. const simulation = d3.forceSimulation(nodes)
  45. .force("link", d3.forceLink(links).id(d => d.id))
  46. .force("charge", d3.forceManyBody())
  47. .force("center", d3.forceCenter(width / 2, height / 2));
  48. simulation.on("tick", () => {
  49. link
  50. .attr("x1", d => d.source.x)
  51. .attr("y1", d => d.source.y)
  52. .attr("x2", d => d.target.x)
  53. .attr("y2", d => d.target.y);
  54. node
  55. .attr("cx", d => d.x)
  56. .attr("cy", d => d.y);
  57. label
  58. .attr("x", d => d.x)
  59. .attr("y", d => d.y - 25);
  60. });
  61. function drag(simulation) {
  62. function dragstarted(event) {
  63. if (!event.active) simulation.alphaTarget(0.3).restart();
  64. event.subject.fx = event.subject.x;
  65. event.subject.fy = event.subject.y;
  66. }
  67. function dragged(event) {
  68. event.subject.fx = event.x;
  69. event.subject.fy = event.y;
  70. }
  71. function dragended(event) {
  72. if (!event.active) simulation.alphaTarget(0);
  73. event.subject.fx = null;
  74. event.subject.fy = null;
  75. }
  76. return d3.drag()
  77. .on("start", dragstarted)
  78. .on("drag",
  79. dragged)
  80. .on("end", dragended);
  81. }
  82. }
  83. }
  84. </script>
  85. <style>
  86. svg {
  87. background-color: #eee;
  88. }
  89. </style>