跳到主要内容

HTML5 Canvas 简单裁剪教程

要使用 Konva 在裁剪区域内绘制内容,可以设置组或图层的 clip 属性。 裁剪区域由 xywidthheight 定义。在本教程中, 我们将在应用到组的矩形裁剪区域内绘制多个圆形。

对于更复杂的情况,请参阅裁剪函数。裁剪函数

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);