Konva – Clip Regions with Holes

Making clip regions with holes can be confusing. I grabbed this simple example by user @Balage1551 from the Konva discord as I thought it was a great example.

TLDR: See the Codepen demo here.

What the video shows is:

  • the stage covered by a fading orange background. In a moment I will drag the clipped group around over this to show that the ‘holes’ really are holes in the group.
  • On top of that we have a green rectangle and a red circle. The circle is draggable. I give it a quick drag to show there are no holes yet.
  • There is a group on the stage – this group has the clipping function defined, but at this point none of the shapes are in the group.
  • When I click the ‘Toggle clip region’ button the green rect and red circle are added to the group. Another click takes them out of the group.
  • With the shapes on the group we can see the effect of the clipping function. I can still drag the circle around, and I can drag the group.

The magic that produces the cut-out / holes effect is the direction of the paths. At line 7 we begin the first ‘hull’ – visible as the top left square on the stage. If you look that the points in the moveTo calls you can see the drawing is top-left -> top-right -> bottom-right -> bottom-left, then the path is closed. Then at line 31 the hole is drawn in the opposite order, meaning from top-left -> bottom-left, etc.

var group = new Konva.Group({
  draggable: true,

  clipFunc: function (ctx) {

    // Start only one path

    // Draw the first hull: clockwise
    ctx.moveTo(50, 50);
    ctx.lineTo(100, 50);
    ctx.lineTo(100, 100);
    ctx.lineTo(50, 100);
    // Closing path, but not starting a new one

    // Draw the second hull: clockwise
    ctx.moveTo(100, 100);
    ctx.lineTo(150, 100);
    ctx.lineTo(150, 150);
    ctx.lineTo(100, 150);

    // Now draw two holes: counterclockwise
    ctx.moveTo(110, 110);
    ctx.lineTo(110, 140);
    ctx.lineTo(140, 140);
    ctx.lineTo(140, 110);

    ctx.moveTo(60, 60);
    ctx.lineTo(60, 90);
    ctx.lineTo(90, 90);
    ctx.lineTo(90, 60);


And that’s all there is to it! @Balage1551 explained it as…

“Complex polygons usually defined in a way where the hulls (outer boundaries) have the same orientation while the holes have to be reversed one. Orientation is the order the vertices in the polygon are defined: clockwise and counter-clockwise. So, to create a polygon with hole, you have to add the polygons with the correct orientation.”

Thanks for reading.

VW March 2022

One thought on “Konva – Clip Regions with Holes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: