Simple tree generator

Click on the screen to generate a new tree.

by Javier Graciá Carpio

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

JavaScript

var sketch = function (p) {
    // Initial setup
    p.setup = function () {
        // Create the canvas
        var canvas = p.createCanvas(600, 450);

        // Paint a new tree each time the mouse is pressed inside the canvas
        canvas.mousePressed(paintNewTree);

        // We will just paint the tree once
        p.noLoop();
        p.noStroke();

        // Paint the tree
        paintNewTree();
    };

    /*
     * This function creates a tree iteratively and paints it in the canvas
     */
    function paintNewTree() {
        var position = p.createVector(0.5 * p.width, 0.95 * p.height, 0);
        var length = p.height / 7;
        var diameter = length / 4.5;
        var angle = -p.HALF_PI + (p.PI / 180) * p.random(-5, 5);
        var color = p.color(130, 80, 20);
        var level = 1;
        var tree = new Branch(position, length, diameter, angle, color, level);

        // Paint the tree
        p.background(245);
        tree.paint();
    }

    /*
     * The Branch class
     */
    function Branch(position, length, diameter, angle, color, level) {
        this.position = position;
        this.length = length;
        this.diameter = diameter;
        this.angle = angle;
        this.color = color;
        this.level = level;
        this.middleBranch = this.createSubBranch(true);
        this.extremeBranch = this.createSubBranch(false);
    }

    /*
     * This method paints the branch and its sub-branches in the canvas
     */
    Branch.prototype.paint = function () {
        // Paint the middle branch
        if (this.middleBranch) {
            this.middleBranch.paint();
        }

        // Paint the extreme branch
        if (this.extremeBranch) {
            this.extremeBranch.paint();
        }

        // Calculate the diameter at the branch top
        var topDiameter = 0.65 * this.diameter;

        if (this.extremeBranch) {
            topDiameter = this.extremeBranch.diameter;
        }

        // Paint the branch
      ...