Drawing Shapes with Holes

Posted on 2013-06-17 by Jan Vantomme
Tags: processing, tutorial

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.

size( 450, 302, P2D );

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.


for ( int i = 0; i < 8; i++ ) {
    float x = cos( i * outerAngle - a ) * outerRadius;
    float y = sin( i * outerAngle - a ) * outerRadius;
    vertex( x, y );

for ( int i = 0; i < 6; i++ ) {
    float x = cos( i * innerAngle + a ) * innerRadius;
    float y = sin( i * innerAngle + a ) * innerRadius;
    vertex( x, y );

endShape( CLOSE );

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