形状组
要使用 Konva 将多个形状组合在一起,我们可以实例化一个 Konva.Group()
对象,然后通过 add()
方法添加形状到该组中。将形状组合在一起在我们想要一起变换多个形状时非常方便,例如,如果我们想一次性移动、旋转或缩放多个形状。组也可以添加到其他组中,以创建更复杂的节点树。
要查看完整属性和方法列表,请查看 Konva.Group 文档。
说明:尝试拖动该组。注意所有形状一起移动。
- Vanilla
- React
- Vue
import Konva from 'konva'; const width = window.innerWidth; const height = window.innerHeight; const stage = new Konva.Stage({ container: 'container', width: width, height: height, }); const layer = new Konva.Layer(); const group = new Konva.Group({ x: 50, y: 50, draggable: true, }); const circle = new Konva.Circle({ x: 40, y: 40, radius: 30, fill: 'red', stroke: 'black', strokeWidth: 4, }); const rect = new Konva.Rect({ x: 80, y: 20, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 4, }); group.add(circle); group.add(rect); layer.add(group); stage.add(layer);
import { Stage, Layer, Group, Circle, Rect } from 'react-konva'; const App = () => { return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Group x={50} y={50} draggable> <Circle x={40} y={40} radius={30} fill="red" stroke="black" strokeWidth={4} /> <Rect x={80} y={20} width={100} height={50} fill="green" stroke="black" strokeWidth={4} /> </Group> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer> <v-group :config="groupConfig"> <v-circle :config="circleConfig" /> <v-rect :config="rectConfig" /> </v-group> </v-layer> </v-stage> </template> <script setup> const stageSize = { width: window.innerWidth, height: window.innerHeight }; const groupConfig = { x: 50, y: 50, draggable: true }; const circleConfig = { x: 40, y: 40, radius: 30, fill: 'red', stroke: 'black', strokeWidth: 4 }; const rectConfig = { x: 80, y: 20, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 4 }; </script>