How to add a Fabric.js object to a Fabric.js group
When adding an existing Fabric.js object to a Fabric.js group be sure to remove the object from the canvas before adding it to the group. Otherwise, the original object will still be draggable and will muck up the group.
In Fabric.js, if you have an existing group, and want to add a Frabic.js Object that's already on the canvas to the group, you have to remove the object from the canvas before adding it to the group, otherwise, the object will still be draggable and you’ll experience strange behavior like clipping and group expansion.
In the demo posted below, you’ll notice three objects: a red rectangle, a blue circle, and some text. The text and the circle are grouped as one and will move together, while the rect moves independently. Pressing the "addToGroup" button will add the rectangle to the existing group, thereby making drags on the rectangle move the whole group (all three objects). Press "ungroup" to undo the grouping.
I also experienced an issue when trying to send an item in a group to the back or to the front. When executing
rect.sendToBack(); the canvas did not update the ordering until I dragged the group. If you want the canvas to update the ordering immediately, you must set dirty to true, then request a canvas redraw. Fabric.js handles visual order by manipulating the array of objects belonging to the group, so
rect.sendToBack() moves the rectangle to position 0 of the group's
_objects array, causing items following it to draw overtop. Press the "addToGroupSendBack" button to see everything be drawn above the rect.
See the Pen fabricjs-add-object-to-group by Sandro Turriate (@sandro) on CodePen.
Try commenting out
canvas.remove(rect); to see what happens when you don’t remove the the object from the canvas before adding it to the group.