Processing Month, Day 13 - Regular Polygons

Posted by Jan Vantomme on 13 May 2011.
Tags: ,

Today we’re going to write a flexible function to draw regular polygons. As Processing only offers basic shapes like ellipses, rectangles and triangles, it might be handy to have a collection of functions to draw other shapes. The function for a regular polygon looks a lot like the algorithm we wrote on day 4, Stars.

The code below is the full function to draw a regular polygon. It takes a float for the radius, and an integer for the number of points.

void regularPolygonfloat radiusint numPoints )
{
    float angle 
TWO_PI numPoints;
    
beginShape();
    for (
int i 0numPointsi++) {
        float x 
cosangle ) * radius;
        
float y sinangle ) * radius;
        
vertexx);
    
}
    endShape
(CLOSE); 

If you want to draw the polygon to the screen, you’ll need to use the @translate()@ function first. The function draws the regular polygon from its center. I’ve used a for-loop to draw a lot of polygons, so you can see how powerful a small function like this one can be.

translatewidth/2height/);
for (
int i 018i++) {
    regularPolygon
10 10);

Examples

The sketch is also available on OpenProcessing.

Some regular polygons made with our flexible function

Download

Download the example for Procesing Day 13, Regular Polygons.

Tweet this article