Working on a simple drag and drop editor. I am adding images:
const addImage = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const img = new window.Image();
img.src = event.target.result;
img.onload = () => {
const aspect = img.width / img.height;
const width = 200;
const newImage = {
id: `image-${Date.now()}`,
type: 'image',
x: 50,
y: 50,
width: width,
height: width / aspect,
image: img,
opacity: 1,
};
setObjects([...objects, newImage]);
};
};
reader.readAsDataURL(file);
};
And this works well. I have done the same for text, but for this purpose, I am trying to group two images.
const groupSelected = () => {
if (selectedIds.length < 2) return;
const groupedNodes = selectedIds.map((id) =>
layerRef.current.findOne(`#${id}`)
);
// Create a new Konva.Group instance
const group = new Konva.Group({
id: `group-${Date.now()}`,
draggable: true,
});
// Add each selected node to the group
groupedNodes.forEach((node) => {
group.add(node);
});
// Add the group to the layer
layerRef.current.add(group);
layerRef.current.batchDraw();
// Clear out the individual nodes that are now grouped
const remainingObjects = objects.filter((obj) => !selectedIds.includes(obj.id));
setObjects([...remainingObjects, { id: group.id(), type: 'group' }]);
// Set the group as selected
setSelectedIds([group.id()]);
};
and my renderObject:
const renderObject = (obj) => {
switch (obj.type) {
case 'image':
return (
<Image
key={obj.id}
id={obj.id}
x={obj.x}
y={obj.y}
width={obj.width}
height={obj.height}
image={obj.image}
draggable
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onTransformEnd={handleTransformEnd}
opacity={obj.opacity}
/>
);
case 'text':
return (
<Text
key={obj.id}
id={obj.id}
x={obj.x}
y={obj.y}
text={obj.text}
fontSize={obj.fontSize}
fontFamily={obj.fontFamily}
fill={obj.fill}
width={obj.width}
height={obj.height}
align={obj.align}
draggable
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onTransformEnd={handleTransformEnd}
fontStyle={obj.fontStyle}
textDecoration={obj.textDecoration}
/>
);
case 'group':
// Check if obj.objects exists and is an array, and provide an empty array if undefined
return (
<Group
key={obj.id}
id={obj.id}
x={obj.x}
y={obj.y}
draggable
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onTransformEnd={handleTransformEnd}
>
{(obj.objects || []).map(renderObject)}
</Group>
);
default:
return null;
}
};
When I group two or more selected objects, they just disappear.
Been struggling on grouping for days. I can make simple versions work but when I try to work it into this, I cannot make it work no matter what I do.
Any help would be much appreciated.
1