Source: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/tree/master/chp08_fractals/NOC_8_06_Tree
<script language="javascript" type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.js">
</script>
JavaScript p5 code
var theta;
function setup() {
var canvas = createCanvas(640, 360);
canvas.parent('sketch-holder');
}
theta = 0;
function draw() {
background(51);
// Let's pick an angle 0 to 90 degrees based on the mouse position
// Start the tree from the bottom of the screen
translate(width/2, height);
stroke(255);
branch(120);
theta = theta + 0.003;
}
function branch(len) {
// Each branch will be 2/3rds the size of the previous one
//float sw = map(len,2,120,1,10);
//strokeWeight(sw);
strokeWeight(2);
line(0, 0, 0, -len);
// Move to the end of that line
translate(0, -len);
len *= 0.66;
// All recursive functions must have an exit condition!!!!
// Here, ours is when the length of the branch is 2 pixels or less
if (len > 2) {
push(); // Save the current state of transformation (i.e. where are we now)
rotate(theta); // Rotate by theta
branch(len); // Ok, now call myself to draw two new branches!!
pop(); // Whenever we get back here, we "pop" in order to restore the previous matrix state
// Repeat the same thing, only branch off to the "left" this time!
push();
rotate(-theta);
branch(len);
pop();
}
}