JSFiddle - React, Tailwind, and code Playground
by Sree K
HTML
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="render"></div>
CSS
#render {
overflow: auto;
text-align: center;
}
#render .node {
cursor: pointer;
}
#render .node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
#render .node text {
font: 16px "Hiragino Sans GB", "华文细黑", "STHeiti", "微软雅黑", "Microsoft YaHei", SimHei, "Helvetica Neue", Helvetica, Arial, sans-serif !important;
}
#render .link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
JavaScript
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 600 - margin.right - margin.left,
height = 400 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree().size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x];
});
var svg = d3.select("#render").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 + ")");
var node = {
name: 'Root',
type: 'root',
children: [{
name: 'A',
type: 'child'
},{
name: 'B',
type: 'child'
},{
name: 'C',
type: 'child'
}]
};
root = node;
root.x0 = height / 2;
root.y0 = 0;
root.children.forEach(collapse);
update(root);
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
function update(source) {
console.log(height);
var newHeight = Math.max(tree.nodes(root).reverse().length * 20, height);
console.log(newHeight);
d3.select("#render svg")
.attr("width", width + margin.right + margin.left)
.attr("height", newHeight + margin.top + margin.bottom);
tree = d3.layout.tree().size([newHeight, width]);
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
nodes.forEach(function (d) {
d.y = d.depth * 180;
});
var node = svg.selectAll("g.node")
.data(nodes, function (d) {
return d.id || (d.id = ++i);
});
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function (d) {
return d.endNode ? "orange" : "lightsteelblue";
});
nodeEnter.append("text")
.attr("x", function (d) {
return 15;
...