形状组
要将多个形状与 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>