Processing Month, Day 4 - Stars

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

Today we'll take a look at creating more complex shapes with Processing. We're going to use beginShape() , endShape() and vertex() to draw a star to the screen. We'll start by declaring some variables we need to calculate all points for the star: the inner radius, the outer radius, the number of spikes and an array to hold all the points. Note that the length of the array is 2 * numSpikes, as we need the same amount of points on the inner radius and on the outer radius of the star.

float innerRadius = 70;
float outerRadius = 180;
int numSpikes = 5;
PVector[] points = new PVector[ numSpikes * 2 ];

Next thing is calculating all points for the star. We need to make sure that we do this in the right order. All even points should be drawn on the outer radius, all odd points on the inner radius. To do this, we'll use the modulo operator. If the remainder of i % 2 is zero, the points will be on the outer radius.

float angle = TWO_PI / points.length;
for ( int i = 0; i < points.length; i++ ) {
    float x, y;
    if ( i % 2 == 0 ) {
        x = cos( angle * i ) * outerRadius;
        y = sin( angle * i ) * outerRadius;
    } else {
        x = cos( angle * i ) * innerRadius;
        y = sin( angle * i ) * innerRadius;
    }
    points[i] = new PVector( x, y );
}

To draw the star to the screen, we will use the beginShape() and endShape() functions to create a real shape from the points we've calculated. We'll use a for-loop between those two functions to iterate through our points array and make a vertex from each of the points. Make sure to use the CLOSE parameter for endShape(), otherwise the star won't be a closed shape. You'll see this when you draw the star with a stroke.

translate( width/2, height/2 );
beginShape();
for (int i = 0; i < points.length; i++) {
    vertex( points[i].x, points[i].y );
}
endShape(CLOSE);

Examples

Star

Star

Star

Star

OpenProcessing

I've been posting the examples on OpenProcessing. The sketch for today can be found over there: Stars, OpenProcessing.

Documentation

Download

Sketch for Processing Month, Day 4

Tweet this article