Sierpinski triangle in D3

2014-02-19 1 min read

    There’s a little known algorithm for constructing a Sierpinski triangle that is surprisingly easy to implement.

    1. Start the three vertices that form a triangle
    2. Pick a random point inside the triangle
    3. Pick a random vertex
    4. Go halfway from a the random point to the vertex and mark that point
    5. Go to step 3 using the result of 4 as the starting point

    I’m trying to get better at D3 and thought it would be a good exercise to code it up. The resulting image is below (generated using 10,000 points) and the JavaScript is in the following file. Next up is to write a new script that allows a user to specify the number of vertices and the adjustment factor - the Sierpinski carpet can be generated with 4 vertices and a distance adjustment factor of a third rather than a half.