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
ctx.beginPath();
// 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
ctx.closePath();
// Draw the second hull: clockwise
ctx.moveTo(100, 100);
ctx.lineTo(150, 100);
ctx.lineTo(150, 150);
ctx.lineTo(100, 150);
ctx.closePath();
// Now draw two holes: counterclockwise
ctx.moveTo(110, 110);
ctx.lineTo(110, 140);
ctx.lineTo(140, 140);
ctx.lineTo(140, 110);
ctx.closePath();
ctx.moveTo(60, 60);
ctx.lineTo(60, 90);
ctx.lineTo(90, 90);
ctx.lineTo(90, 60);
ctx.closePath();
}
});
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”