Last active
May 30, 2016 16:47
-
-
Save darrenjaworski/aec2296a57b729f1e0defe00d95a44b6 to your computer and use it in GitHub Desktop.
D3 Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment