D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
darrenjaworski
Full window
Github gist
D3 Tree
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css"> </head> <body> <button onclick="drawTree.init()">Recreate tree!</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script> <script> var drawTree = { height: window.innerHeight, width: window.innerWidth, maxDepth: 13, branchColor: d3.scale.linear().domain([13, 0]).range(["#582411", "#A9D8DA"]), svg: d3.select('body').append('svg').attr('width', window.innerWidth).attr('height', window.innerHeight), init: function(){ drawTree.svg.selectAll('rect').remove() drawTree.generateTree(drawTree.width / 2, drawTree.height * .95, drawTree.width * .1, 25, Math.PI, drawTree.maxDepth); }, generateTree: function(x, y, length, width, angle, depth){ if (depth == 0) { return; } var branchData = { x: x, y: y, length: length, width: width, angle: angle, depth: depth }; var branch = drawTree.svg.append('rect').datum(branchData) .attr('x', function(d) { return d.x; }) .attr('y', function(d) { return d.y }) .attr('height', function(d) { return d.length; }) .attr('width', function(d) { return d.width; }) .attr('transform', function(d) { return 'rotate('+ (d.angle * (180 / Math.PI)) +' '+ d.x +' '+ d.y +')'; }) .attr('fill', function(d) { return drawTree.branchColor( d.depth ); }); var endx = x - length * Math.sin(angle); var endy = y + length * Math.cos(angle); var newlength = length * .8; var newwidth = width * .8; var newangle = angle + Math.random() * ( Math.PI / 2) - ( Math.PI / 2) * .5; var newdepth = depth - 1; var branchNumber = ~~(Math.random() * 3) + 1; for (var i = 0; i < branchNumber; i++) { drawTree.generateTree(endx, endy, newlength, newwidth, newangle, newdepth); } } }; drawTree.init() </script> </body> </html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js