Working with the PShape class

Posted by Jan Vantomme on 23 June 2013.
Tags: ,

A great new feature in Processing 2 is the PShape class. You can use it to store a shape, as well as its appearance. In this article, we’ll take a look at creating basic shapes like a rectangle and an ellipse, and how we can create our own custom shapes.

The first thing we need to do is to declare some PShape variables, right before the setup() function.

PShape rectangle;
PShape circle

Inside the setup() function, we’ll create the shapes. The first parameter is the type of shape, then you have the x and y coordinates of the shape, and the width and height.

rectangle createShapeRECT4080160160 );
circle createShapeELLIPSE25080160160 ); 

To change the appearance of these shapes, you can use the setFill(), setStroke() and setStrokeWeight() methods of the PShape class.

rectangle.setFill#FF823A );
rectangle.setStroke#F04155 );
rectangle.setStrokeWeight);  
circle.setFill#95CFB7 );
circle.setStrokefalse ); 

In the draw() function, you can draw your shapes with the shape() function. The result should look like this.

Basic PShapes

If you want to create your own custom shapes, you’ll need to create an empty shape, and add vertices to it. This is the code to create a hexagon shape.

hexagon createShape();
hexagon.beginShape();
for ( 
int i 06i++ ) {
    float x 
cosTHIRD_PI ) * 20;
    
float y sinTHIRD_PI ) * 20;
    
hexagon.vertexx);
}
hexagon
.endShapeCLOSE );

hexagon.setFillcolor25564 ) );
hexagon.setStrokecolor#0E8D94, 128 ) ); 

This shape will be drawn at (0, 0). In the draw() function, I’ve used the translate() function to move the point to where the mouse pointer is, so you can paint with the custom shape you’ve just created. The result looks like this.

A custom hexagon made with the PShape class

Note that not every method of the PShape class is documented in the Processing 2 reference. If you want to know everything you can do with it, you should check out the JavaDoc for PShape.

The code for this tutorial can be found in the GitHub Repository for this series of articles.

Tweet this article