Iterative Sierpinksi Fractal (drawn on HTML5 Canvas)

So maybe you’ve seen this very famous fractal called the Sierpinksi Fractal.

A few days ago I heard that you could create this fractal pattern by simply plotting out of a random sequence of mid points of an ever growing set of these mid points. So curiosity added with my apetite for playing with the HTML5 Canvas object and you have me playing on a saturday afternoon and then blogging about it.

Drawing this thing

Usually you’d think of drawing the Sierpinski Triangle the Recursive way, specially if you’re a CS student. The algorithm would be basically… For each triangle you create 3 triangles, one on top, one on the left, and one on the right (in the order that you want), repeat and rinse for each new triangle (until you decide to stop… you can use for example the height of the next triangle to stop, if too small stop)

But then I heard on some online video lecture about fractals that you could obtain the same results in an iterative fashion, no recursion whatsoever, just generate point after point randomly following one basic rule.

Choose 3 points in a plane, then choose 2 random points of the 3 and draw the middle point of these 2. Do the same for the new set of points. If the 3 initial points represent the vertices of a triangle you have yourself a Sierpinski fractal triangle. If you don’t choose an initial triangle, you’ll also get Sierpinski but it looks as if you were looking at the triangle from a random angle.

I must say I was pretty amazed when I saw it working… TADA!!!!


Try it on your browser
(Tested and works under Firefox 3.5, Chromium 4.0.2, and Safari)

That’s how it looks when you draw 800k random mid points.

PS: It runs faster in Chrome, props to Chrome developers.