Drawing Shapes with Holes

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

In Processing 1.5.1, there was a function named breakShape(). It was undocumented, and only worked in the default Java2D mode. This function allowed you to draw shapes with holes. Processing 2 has some new functions to create these kinds of shapes. And they are much more stable. Let’s take a look at how they work.

First of all, you need to set the renderer to P2D in setup(). If you forget this, it won’t work.

size450302P2D ); 

To draw custom shapes, you can start by using beginShape() and endShape(), just like you would normally do. Don’t forget to add the CLOSE parameter to endShape(). The next thing we’ll do is add some vertices to draw an octagon for the outer shape. Once this is done, we’ll use the new beginContour() and endContour() functions. Between these functions we’ll add some vertices to draw a hexagon. This hexagon will be the hole in our shape.

beginShape();

for ( 
int i 08i++ ) {
    float x 
cosouterAngle ) * outerRadius;
    
float y sinouterAngle ) * outerRadius;
    
vertexx);
}

beginContour
();
for ( 
int i 06i++ ) {
    float x 
cosinnerAngle ) * innerRadius;
    
float y sininnerAngle ) * innerRadius;
    
vertexx);
}
endContour
();

endShapeCLOSE ); 

Note that you can only draw shapes with vertices if you want to do something like this. Functions like rect() or ellipse() can’t be used to create these kinds of shapes. This is what the result looks like. The code can be found in the Processing 2 tutorial repository on GitHub.

An octagon with a hexagon hole.

An octagon with a hexagon hole.

Tweet this article