Processing Month, Day 6 - Square Flowers, Part 2

Posted on 2011-05-06 by Jan Vantomme
Tags: processing, tutorial

For the first five days, we've only drawn one object to the screen. Today we are going to take a look at how we can write a flexible function so we can draw multiple flowers to the screen.

We'll start by defining a function at the bottom of our sketch, right after the draw() function. The void keyword before the name of the function means that the function doesn't return a value.

void squareFlower()
{
}

The next thing is to setup some variables between the curly brackets of our function. We need the same variables as in Square Flowers - Part 1, and an extra variable for the color.

float x = random(width);
float y = random(height);
float steps = floor( random(10, 20) );
float angle = random( 8, 20 );
float startSize = random(80, 120);
color c = color( 128 + random(128), 0, 0);

To draw the flower to the screen we'll use the algorithm we used yesterday, but need to add two important functions: pushMatrix() and popMatrix(). If we don't use pushMatrix() before translate(), we'll only be able to draw the first flower inside draw() on the right coordinates. That's ok if you only draw one flower each frame, but if you want to draw more flowers, you'll need to use pushMatrix() and popMatrix().

stroke( c );
fill( 0 );
pushMatrix();
translate(x, y);
for ( int i = 0; i < steps; i++ ) {
    rotate( radians( angle * i ) );
    rect( 0, 0, startSize - 5*i, startSize - 5*i);
}
popMatrix();

Now that our function is ready, we can call drawFlower() inside draw(), so our sketch will draw a flower each frame. If you want to draw more flowers each frame, you'll need to call drawFlower() more than once, preferably with a for-loop.

Examples.

This example is also available at OpenProcessing.

Square Flowers, Made with Processing

Square Flowers, Made with Processing

Download

Sketch for Processing Month, Day 6

Tweet this article