This example is for Processing 2+. If you have a previous version, use the examples included with your software. If you see any errors or have suggestions, please let us know.

Recursive Tree by Daniel Shiffman.

Renders a simple tree-like structure via recursion. The branching angle is calculated as a function of the horizontal mouse location. Move the mouse left and right to change the angle.

float theta;   

void setup() {
  size(640, 360);

void draw() {
  // Let's pick an angle 0 to 90 degrees based on the mouse position
  float a = (mouseX / (float) width) * 90f;
  // Convert it to radians
  theta = radians(a);
  // Start the tree from the bottom of the screen
  // Draw a line 120 pixels
  // Move to the end of that line
  // Start the recursive branching!


void branch(float h) {
  // Each branch will be 2/3rds the size of the previous one
  h *= 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 (h > 2) {
    pushMatrix();    // Save the current state of transformation (i.e. where are we now)
    rotate(theta);   // Rotate by theta
    line(0, 0, 0, -h);  // Draw the branch
    translate(0, -h); // Move to the end of the branch
    branch(h);       // Ok, now call myself to draw two new branches!!
    popMatrix();     // 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!
    line(0, 0, 0, -h);
    translate(0, -h);