JSFiddle - React, Tailwind, and code Playground
HTML
<div id="node"></div>
CSS
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 2px;
}
.node text {
font: 12px sans-serif;
fill: black;
}
.link {
fill: none;
/* stroke: white; */
stroke-width: 1.5px;
}
svg {
pointer-events: all;
}
JavaScript
var data = {
"name": "root",
"children": [{
"name": "leaf1"
}, {
"name": "leaf2"
}]
};
buildTree(data);
var svg;
function buildTree(data) {
var i = 0,
root;
root = data;
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 960 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x];
});
svg = d3.select("#node").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.x0 = height / 2;
root.y0 = 0;
var zb = d3.behavior.zoom().scaleExtent([0.5, 5]).on("zoom", function () {
zoom();
});
zb.translate([margin.left, margin.top]);
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
function expand(d) {
if (d._children && d.depth < 4) {
d.children = d._children;
d._children.forEach(expand);
d._children = null;
}
}
d3.select("svg").call(zb);
root.children.forEach(collapse);
update(root);
function update(source) {
var duration = d3.event && d3.event.altKey ? 5000 : 500;
var levelWidth = [1];
var childCount = function (level, n) {
if (n.children && n.children.length > 0) {
if (levelWidth.length <= level + 1) levelWidth.push(0);
levelWidth[level + 1] += n.children.length;
n.children.forEach(function (d) {
childCount(level + 1, d);
...