DEV Community

[Comment from a deleted post]
Collapse
 
loderunner profile image
Charles Francoise

Funny, I was just playing with fractals on canvas the other day. Specifically the Barnsley Fern. I think it's a very interesting way to build and understand fractal structures. Also, it's great to see them build up pixel per pixel.

Here's my quick & dirty implementation.

// mathjs (http://mathjs.org) imported in the HTML

const transformations = [
    { p : 0.03, m : [[0, 0], [0, 0.16]], n : [0, 0] },
    { p : 0.85, m : [[0.85, 0.04], [-0.04, 0.85]], n : [0, 1.60] },
    { p : 0.06, m : [[0.20, -0.26], [0.23, 0.22]], n : [0, 1.60] },
    { p : 0.06, m : [[-0.15, 0.28], [0.26, 0.24]], n : [0, 0.44] }
]

function transform(pos)
{
    r = math.random()
    for (t of transformations)
    {
        if (r < t.p) {
            return math.add(math.multiply(t.m, pos), t['n'])
        } else {
            r -= t.p
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
    // 800x600 canvas element created in the HTML
    const context = document.getElementById('canvas').getContext('2d')
    var pos = [0, 0]
    window.setInterval(() => {
        context.save()
        context.transform(1, 0, 0, -1, 400, 600)        // flip the canvas vertically, and set origin to bottom middle
        context.fillRect(pos[0]*50, pos[1]*50, 1, 1)    // scale pos by 50
        pos = transform(pos)
        context.restore()
    }, .01)
})
Enter fullscreen mode Exit fullscreen mode