David Johnstone

Barnsley's Fern

I recently discovered Barnsley's Fern and was impressed by the way a relatively straight-forward bit of code could draw such a pretty picture. I can't claim to be an expert at this, but this is related to fractals and is a form of chaos game.

Anyway, this seemed like a fun thing to draw on a HTML5 canvas, which means that this is taking a black rectangle and drawing 180,000 green dots on it. It also means that if you refresh, the image will subtly change because of the randomness in pixel placement. Some of the code here is related to this Python implementation.

The important part of the code looks a bit like:

for (var i = 0; i < 180000; i++) {
    var rand = Math.random();
    if (rand < 0.01) {
        x = 0;
        y = 0.0, 0.16 * y;
    }
    else if (rand < 0.84) {
        newx = (0.85 * x) + (0.04 * y);
        newy = (-0.04 * x) + (0.85 * y) + 1.6;
        x = newx;
        y = newy;
    }
    else if (rand < 0.92) {
        newx = (0.2 * x) - (0.26 * y);
        newy = (0.23 * x) + (0.22 * y) + 1.6;
        x = newx;
        y = newy;
    }
    else {
        newx = (-0.15 * x) + (0.28 * y);
        newy = (0.26 * x) + (0.24 * y) + 0.44;
        x = newx;
        y = newy;
    }
    drawPoint(x, y);
}