HTML5 Canvas 简单裁剪教程
使用 Konva 在裁剪区域内绘制内容的方法是,我们可以设置组或图层的 clip
属性。
裁剪区域由 x
、y
、width
和 height
定义。在本教程中,我们将在应用到组的矩形裁剪区域内绘制 blob。
对于更复杂的情况,可以查看裁剪函数。裁剪函数
- Vanilla
- React
- Vue
import Konva from 'konva'; // 首先需要创建舞台 const stage = new Konva.Stage({ container: 'container', width: window.innerWidth, height: window.innerHeight, }); // 然后创建图层 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); } // 将组添加到图层 layer.add(group); // 将图层添加到舞台 stage.add(layer);
import { Stage, Layer, Group, Circle } from 'react-konva'; const App = () => { const blobs = Array.from({ length: 20 }, (_, i) => ({ x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight, radius: Math.random() * 50, })); return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Group clip={{ x: 100, y: 20, width: 200, height: 200, }} > {blobs.map((blob, i) => ( <Circle key={i} x={blob.x} y={blob.y} radius={blob.radius} fill="green" opacity={0.8} /> ))} </Group> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer> <v-group :config="groupConfig"> <v-circle v-for="(blob, i) in blobs" :key="i" :config="blob" /> </v-group> </v-layer> </v-stage> </template> <script setup> const stageSize = { width: window.innerWidth, height: window.innerHeight }; const groupConfig = { clip: { x: 100, y: 20, width: 200, height: 200, } }; const blobs = Array.from({ length: 20 }, () => ({ x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight, radius: Math.random() * 50, fill: 'green', opacity: 0.8 })); </script>