Working with the PShape class
Posted on 2013-06-23 by Jan Vantomme
Tags:
processing, tutorial
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 = createShape( RECT, 40, 80, 160, 160 );
circle = createShape( ELLIPSE, 250, 80, 160, 160 );
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( 4 );
circle.setFill( #95CFB7 );
circle.setStroke( false );
In the draw()
function, you can draw your shapes with the shape()
function. The result should look like this.
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 = 0; i < 6; i++ ) {
float x = cos( i * THIRD_PI ) * 20;
float y = sin( i * THIRD_PI ) * 20;
hexagon.vertex( x, y );
}
hexagon.endShape( CLOSE );
hexagon.setFill( color( 255, 64 ) );
hexagon.setStroke( color( #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.
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.