图形组
要使用 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';
import { useState } from 'react';
const App = () => {
const [position, setPosition] = useState({ x: 50, y: 50 });
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Group
x={position.x}
y={position.y}
draggable
onDragEnd={(e) => {
setPosition({ x: e.target.x(), y: e.target.y() });
}}
>
<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>