Skip to main content

HTML5 Canvas Simple Clipping tutorial

To draw things inside of clipping regions with Konva, we can set the clip property of a group or a layer. Clipping regions are defined by an x, y, width, and height. In this tutorial, we'll draw blobs inside of a rectangular clipping region applied to a group.

For more complex cases take a look into clipping function. Clipping Function

import Konva from 'konva';

// First we need to create stage
const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

// Then create layer
const layer = new Konva.Layer();

const group = new Konva.Group({
  clip: {
    x: 100,
    y: 20,
    width: 200,
    height: 200,
  },
});

for (let i = 0; i < 20; i++) {
  const blob = new Konva.Circle({
    x: Math.random() * stage.width(),
    y: Math.random() * stage.height(),
    radius: Math.random() * 50,
    fill: 'green',
    opacity: 0.8,
  });
  group.add(blob);
}

// add the shape to the layer
layer.add(group);

// add the layer to the stage
stage.add(layer);