Shape Groups
To group multiple shapes together with Konva, we can instantiate a Konva.Group() object and then add shapes to it with the add() method.
Grouping shapes together is really handy when we want to transform multiple shapes together, e.g. if we want to move, rotate, or scale multiple shapes at once.
Groups can also be added to other groups to create more complex Node trees.
For a full list of attributes and methods, check out the Konva.Group documentation.
Instructions: Try to drag the group. Notice how all shapes move together.
- 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>