Is my fractal optimized? Could it animate?

If you would like to implement a recursion and animate it, one possible strategy would be as follows:

  • Within the recursive function, save the specifications of each part of the fractal as data rather than actually draw it.
  • From within setup(), call the recursive function. The data will then get saved.
  • Call frameRate() to set the rate of the animation.
  • From draw(), fetch the specifications for one part of the fractal during each frame, and render that part.
  • Call noLoop() after all parts of the fractal have been rendered.

I like Python, and so used Python Mode to implement @josephh’s circles fractal based on the above strategy. Here’s the code:

params = [] # each item will be a list of specs for a circle
def setup():
    size(400, 400)
    background(255)
    noFill()
    frameRate(10)
    recursive_circle(width / 2, height / 2, 200, 4)

def draw():
    if frameCount <= len(params):
        item = params[frameCount - 1]
        circle(item[0], item[1], item[2])
    else:
        noLoop()

def recursive_circle(x, y, d, level):
    # params.append([x, y, d])
    if level == 0:
        # base case; do nothing
        pass
    else:
        # recursive case
        recursive_circle(x - d / 2, y, d / 2, level - 1)
        recursive_circle(x, y - d / 2, d / 2, level - 1)
        recursive_circle(x + d / 2, y, d / 2, level - 1)
        recursive_circle(x, y + d / 2, d / 2, level - 1)
    params.append([x, y, d])

Here’s a screen capture of the process partway through its execution:

1 Like