Using Recursive Graphics to Create a Fractal Tree

By Josh Marinacci, September 22, 2008

Graphics in JavaFX are highly nested thanks to the CustomNode and Group classes. The abundant nesting makes recursive algorithms very easy to build.

Understanding the Code

This example shows how to create a fractal tree using recursive graphics. The RecursiveTree class extends CustomNode, so it must define the create():Node function. In this case, however, create will delegate to a recursive version which will produce nested groups of lines. At each level create function rotates slightly to the right or left and translates so that the new line starts at the end of the old line. It also modifies the color slightly for each level of the tree.

RecursiveTree.fx Class

Source Code
package fractaltree;

import javafx.gui.*;

public class RecursiveTree extends CustomNode {
    public attribute x = 0;
    public attribute y = 100;
    public attribute startDepth: Number = 3;
    public attribute leftFactor = 1.12;
    public attribute rightFactor = 1.6;
    public attribute leftAngle = 20;
    public attribute rightAngle = -45;

    public function create():Node {
        return Group {
            translateX: bind x
            translateY: bind y
            content: [
                create(startDepth, 0)
            ]
        }
    }
    
    private function create(depth:Number, angle:Number):Node {
        var color = (depth*255/startDepth);
        var g = Group {
            transform:  Transform.rotate(angle, 0, 0),
            content: Line { 
                x1:0 y1:0 x2:0 y2:-depth*7 
                stroke: Color.rgb(color,color,0) 
            }
        };
        
        // recurse
        if(depth >= 1) {
            insert Group {
                transform: Transform.translate(0,-depth*7)
                content: [
                    create(depth/leftFactor,leftAngle),
                    create(depth/rightFactor,rightAngle)
                ]
            } into g.content;
        }
        
        return g;
    }
}

If you create RecursiveTree with the default values it looks like Figure 1.

Source Code
RecursiveTree { x: 50 y: 100 }


Figure 1: Default Fractal Tree

However, by tweaking the parameters you can obtain different effects, such as the effects shown in figures 2 through 4.

Source Code
RecursiveTree { 
    x: 100 y: 100
    leftAngle: 30
    rightAngle: -30
    leftFactor: 1.25
    rightFactor: 1.25
}


Figure 2: Symmetric Tree

Source Code
RecursiveTree { 
    x: 100 y: 100
    leftAngle: 0
    rightAngle: -45
    leftFactor: 1.3
    rightFactor: 1.5
}


Figure 3: Flat Tree

Source Code
RecursiveTree { 
    x: 100 y: 100
    leftAngle: 45
    rightAngle: -45
    leftFactor: 1.3
    rightFactor: 1.3
}


Figure 4: 45-Degree Tree