Draw function, Processing, Python

One possible strategy would be to refactor your code so that the variables or other specifications that are currently updated in your loop are instead updated with each call of the draw() function. Below is a simple example of refactoring.

Suppose we would like to draw some rectangles in cycles of 10. We draw 1 rectangle, then erase it and draw 2, then erase them and draw 3, et cetera. We could try this, but it does not work as intended:

def setup():
    size(400, 400)
    rectMode(CENTER)
    frameRate(1)

def draw():
    background(127)
    for i in range(10):
        background(127)
        for j in range(i):
            rect(random(100, 300), random(100, 300), 100, 100)

Refactoring the code as described above, we do this with the draw() function instead, which works as intended:

def draw():
    background(127)
    for i in range(frameCount % 10 + 1):
        rect(random(100, 300), random(100, 300), 100, 100)
1 Like