Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ungroup programatically grouped objects in fabric.js (simply past this code into the "execute" tab of fabricjs kitchensink demo)
// 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();
@pjmartorell
Copy link

pjmartorell commented Mar 17, 2017

In order to avoid using private methods, the following lines:

// ungrouping is here
var items = group._objects;
group._restoreObjectsState();

Could be replaced for:

// ungrouping is here
var items = group.getObjects();
group.destroy();

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment