123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Collapsible Tree Example</title>
- <style>
- .node circle {
- fill: #fff;
- stroke: steelblue;
- stroke-width: 3px;
- }
- .node text { font: 12px sans-serif; }
- .link {
- fill: none;
- stroke: #ccc;
- stroke-width: 2px;
- }
-
- </style>
- </head>
- <body>
- <!-- load the d3.js library -->
- <script src="http://d3js.org/d3.v3.min.js"></script>
-
- <script>
- var treeData = [
- {
- "name": "Top Level",
- "parent": "null",
- "children": [
- {
- "name": "Level 2: A",
- "parent": "Top Level",
- "children": [
- {
- "name": "Son of A",
- "parent": "Level 2: A"
- },
- {
- "name": "Daughter of A",
- "parent": "Level 2: A"
- }
- ]
- },
- {
- "name": "Level 2: B",
- "parent": "Top Level"
- }
- ]
- }
- ];
- // ************** Generate the tree diagram *****************
- var margin = {top: 40, right: 120, bottom: 20, left: 120},
- width = 960 - margin.right - margin.left,
- height = 500 - margin.top - margin.bottom;
-
- var i = 0;
- var tree = d3.layout.tree()
- .size([width, height]);
- var diagonal = d3.svg.diagonal();
- var svg = d3.select("body").append("svg")
- .attr("width", width + margin.right + margin.left)
- .attr("height", height + margin.top + margin.bottom)
- .append("g")
- .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
- root = treeData[0];
-
- update(root);
- function update(source) {
- // Compute the new tree layout.
- console.log(source);
- var nodes = tree.nodes(source).reverse(),
- links = tree.links(nodes);
- // Normalize for fixed-depth.
- nodes.forEach(function(d) { d.y = d.depth * 100; });
- // Declare the nodes…
- var node = svg.selectAll("g.node")
- .data(nodes, function(d) { return d.id || (d.id = ++i); });
- // Enter the nodes.
- var nodeEnter = node.enter().append(function(n) {console.log(n); return document.createElementNS("http://www.w3.org/2000/svg", "g");})
- .attr("class", "node")
- .attr("transform", function(d) {
- return "translate(" + d.x + "," + d.y + ")"; });
- nodeEnter.append("circle")
- .attr("r", 10)
- .style("fill", "#fff");
- nodeEnter.append("text")
- .attr("y", function(d) {
- return d.children || d._children ? -18 : 18; })
- .attr("dy", ".35em")
- .attr("text-anchor", "middle")
- .text(function(d) { return d.name; })
- .style("fill-opacity", 1);
- // Declare the links…
- var link = svg.selectAll("path.link")
- .data(links, function(d) { return d.target.id; });
- // Enter the links.
- link.enter().insert("path", "g")
- .attr("class", "link")
- .attr("d", diagonal);
- }
- </script>
-
- </body>
- </html>
|