Processing Month, Day 4 - Stars

Posted by Jan Vantomme on 04 May 2011.

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 0points.lengthi++ ) {
    float x
    if ( 
== {
cosangle ) * outerRadius;
sinangle ) * outerRadius;
else {
cosangle ) * innerRadius;
sinangle ) * innerRadius;
= new PVectorx);

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.

for (
int i 0points.lengthi++) {







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



Sketch for Processing Month, Day 4

Tweet this article

Oldskool Comments (2)

Gravatar for Raymond Rogers

From: Raymond Rogers
Date: 05.05.2011

Your listing above doesn't match the downloaded sketch book. In fact the listing doesn't run. It stops at points<i> = new PVector( x, y ); Apparently <> should be [] Ray

Top · Permanent link to this comment

Gravatar for Jan Vantomme

From: Jan Vantomme
Date: 05.05.2011

Thanks for noticing. I'm using Textile to format my blog posts and apparently it has some problems with code. I'll try to fix it when I have the time.

Top · Permanent link to this comment