Barnsley Fern

An implementation of a Barnsley Fern based on rosettacode.org/wiki/barnsley_fern

Log in to post a comment.

// Config
const points = [];
const turtle = new Turtle();
let x = 0;
let y = 0;
let newX = 0;
let newY = 0;

// Create Array of Point Coordinates
for (var i=0; i < 100000; i++){
    let rand = Math.random();
    
    if( rand <= 0.01 ){
        newX = 0;
        newY = 0.16*y;
    } else if ( rand <= 0.86) {
        newX = 0.85*x + 0.04*y;
        newY = ((0.04*-x) + 0.85*y + 1.6);
    } else if ( rand <= 0.93 ) { 
        newX = (0.2*x) - (0.26*y);
        newY = 0.23*x + 0.22*y + 1.6;
    } else {
        newX = -0.15*x + 0.28*y;
        newY = 0.26*x + 0.24*y + 0.44;
    }
    
    points.push([newX,-newY]);
    x = newX;
    y = newY;
}

// Draw Point Helper Function
const drawPoint = (coord) => {
    let [x,y] = coord;
    let scale = 15;
    let xOffset = 0;
    let yOffset = 0;
    x = x*scale;
    y = y*scale;
    turtle.penup();
    turtle.goto(x,y);
    turtle.pendown();
    turtle.goto(x,y+.01);
    turtle.goto(x+.01,y+.01);
    turtle.goto(x+.01,y);
    turtle.goto(x,y);
    turtle.penup();
}

// Set Offset
let yOff = 5;
let xOff = 0;
const offSetPoints = points.map( ([x,y]) => [x+xOff,y+yOff])

// Draw each point
offSetPoints.forEach(coord => drawPoint(coord));