Recursive Circles and the Sierpinski Triangle


Dive into the world of recursive functions and fractals by creating an iconic fractal figure - a Serpinski Triangle.
To see a working example click here


Directions
  1. Set up your HTML page, insert the P5.js source tags into the <head>section of your project page:

    <script src= "https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
    <script src= "http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.6/addons/p5.dom.js"></script>

    Your code now speaks P5!

  2. In the setup function, create a canvas and draw a circle in the middle of the screen.

  3. Move the circle into a function. Create a function -- drawCircle -- that, given an x and y position and diameter d, draws a circle.

  4. Now, lets make the function recursive. Add a call inside the drawCircle function calling itself but with the x position and diameter decreasing it in size.

  5. In case you got a "maximum call-stack exceeded" error, add an exit condition where you loop only if the diameter is above a certain limit.

  6. Now make a second call that creates circles on the opposite side. So each circle will have two smaller ones around it.

  7. Add a slider element above your canvas and make the diameter variable a function of the slider value.
    
        diameter=slider.value()
     
    
  8. Finally, add a third direction, call the function recursively while shifting the circle down (or up) on the Y axis. The result should be the famous Sierpinski Triangle, formed out of recursive circles.

  9. Try different combinations with the number of recursive shifts you do and what kinds of shapes this creates. How is the recursive function creating complex shapes?

  10. Test and finish the project till it looks perfect to you.





(c) 2018 by Code Craft Academy