Search code examples
fabricjs

Fabric js select object in group


Is it possible to select a single object from a group created like this?

var r = new fabric.Rect(...);
var l = new fabric.Line(...);
var roadGroup = new fabric.Group([r,l],{ ... });

So I want to have a group, but select objects l or r separately.


Solution

  • The simple answer is yes, but you should make sure you take into account the purpose of a group.

    To get a handle on an object that is wrapped in a group you can do something like this:

    var r = roadGroup._objects[0];
    var l = roadGroup._objects[1];
    

    To select a child of a group try something like this:

    fabricCanvas.setActiveObject(roadGroup._objects[0]);
    

    soapbox:

    The purpose of creating a group is to treat several objects as if they were a single one. The purpose of selecting an object is to allow user interactions with an object. If you want your user to interact with a portion of a group, you might want to consider not grouping them in the first place, or else un-grouping them prior to selecting the child object.

    /soapbox