I wanted to group some objects, manipulate that group (center, rotate) and ungroup the objects in order to handle events on each object, rather that on the whole group. I spent some time to get this working, so I think, it’s worth sharing.
tl;dr
// grab the items from the group you want to "ungroup" items = group._objects; // translate the group-relative coordinates to canvas relative ones group._restoreObjectsState(); // remove the original group and add all items back to the canvas canvas.remove(group); for(var i = 0; i < items.length; i++) { canvas.add(items[i]); } // if you have disabled render on addition canvas.renderAll();
I’ve created a short demo gist, which can be execute withing fabric’s kitchensink demo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// clear canvas | |
canvas.clear(); | |
// add red rectangl | |
canvas.add(new fabric.Rect({ | |
width: 50, height: 50, left: 50, top: 50, fill: 'rgb(255,0,0)' | |
})); | |
canvas.add(new fabric.Rect({ | |
width: 50, height: 50, left: 110, top: 50, fill: 'rgb(255,0,0)' | |
})); | |
var group = new fabric.Group([ | |
canvas.item(0).clone(), | |
canvas.item(1).clone() | |
]); | |
canvas.clear().renderAll(); | |
canvas.add(group); | |
// move group, rotate group | |
group.centerH(); | |
group.centerV(); | |
group.rotate(70); | |
// ungrouping is here | |
var items = group._objects; | |
group._restoreObjectsState(); | |
canvas.remove(group); | |
for(var i = 0; i < items.length; i++) { | |
canvas.add(items[i]); | |
} | |
canvas.renderAll(); |