123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Force Layout</title>
- <style type="text/css">
- .links line {
- stroke: #999;
- stroke-opacity: 0.6;
- }
- .nodes circle {
- fill: #fff;
- pointer-events: all;
- stroke: #000;
- stroke-width: 1.5;
- }
- .nodes .child {
- fill: #000;
- stroke: #fff;
- }
- </style>
- </head>
- <body>
- <script src="d3.v7.min.js"></script>
- <div id="svgContainer"></div>
- <script type="text/javascript">
- const width = 1024;
- const height = 768;
- const svg = d3.select("#svgContainer").append("svg")
- .attr("width", width)
- .attr("height", height);
- drag = simulation => {
-
- function dragstarted(event, d) {
- if (!event.active) simulation.alphaTarget(0.3).restart();
- d.fx = d.x;
- d.fy = d.y;
- }
- function dragged(event, d) {
- d.fx = event.x;
- d.fy = event.y;
- }
- function dragended(event, d) {
- if (!event.active) simulation.alphaTarget(0);
- d.fx = null;
- d.fy = null;
- }
- return d3.drag()
- .on("start", dragstarted)
- .on("drag", dragged)
- .on("end", dragended);
- }
- d3.json("data.json").then(function(data) {
- const root = d3.stratify().path(d => d)(data);
- const links = root.links();
- const nodes = root.descendants();
- //console.log(root);
- //console.log(links);
- //console.log(nodes);
- const simulation = d3.forceSimulation(nodes)
- .force("link", d3.forceLink(links).id(d => d.id).distance(10).strength(1))
- .force("charge", d3.forceManyBody().strength(-50))
- .force("x", d3.forceX())
- .force("y", d3.forceY())
- .force("center", d3.forceCenter(width / 2, height / 2));
- const link = svg.append("g")
- .attr("class", "links")
- .selectAll("line")
- .data(links)
- .join("line");
- const node = svg.append("g")
- .attr("class", "nodes")
- .selectAll("circle")
- .data(nodes)
- .join("circle")
- .attr("class", d => d.children ? null : "child")
- .attr("r", 3.5)
- .call(drag(simulation));
- node.append("title").text(d => d.data);
- const zoom = d3.zoom()
- .scaleExtent([1, 8])
- .on('zoom', function(e) {
- console.log("zoom");
- link.attr('transform', e.transform);
- node.attr('transform', e.transform);
- });
- svg.call(zoom);
- simulation.on("tick", () => {
- link
- .attr("x1", d => d.source.x)
- .attr("y1", d => d.source.y)
- .attr("x2", d => d.target.x)
- .attr("y2", d => d.target.y);
- node
- .attr("cx", d => d.x)
- .attr("cy", d => d.y);
- });
- });
-
- </script>
- </body>
- </html>
|