..Group… what does it remind you of? When I think of the word “group” it reminds me of my short-lived high-school friend-group lol, it also reminds me of my favorite K-Pop gg which is a four-member group and somehow, it reminds me of a group of ducks❔❔❔
Anyways, in all of those cases, it is always a collection of many people or ducks.
In case of FabricJS, groups are a collection of objects clustered together such that they become a single entity.
Creating a group in FabricJS
In order to create a group we need to initiate an instance of fabric.Group 🙄 I know you saw that coming!
Let’s see the constructor definition:
new fabric.Group( objects: Object,
options(optional): Object,
isAlreadyGrouped(optional): Boolean)
// The first argument is where we need to pass
// the objects that we want to be grouped
In the gif below, an image, text and circle have been grouped. Teehee Can you spot all three? ;] It should be noted that when I select the group, all the objects are selected collectively and the same goes for any modifications.
The logic behind creating groups is that you need to create the objects and then add the singular objects to fabric.Group in order to group them.
You can also pass optional properties to the fabric.Group options Object like how here I have added left, top and angle properties:
var group = new fabric.Group([circle, image, text], {
left: 70,
top: 94,
angle: -10,
});
canvas.add(group);
Creating a group of Two Objects
In this example below, I have demonstrated how we can create a group of two objects.
By default, the group members are positioned at the top-left corner of the group. This is why we need to set the originX and originY properties as “center” in order for them to be centered within the group.
You can see that in fabric.Group, the first argument is an array of Objects. Further the group has top-left position of 100-150 and an angle of -10.
var canvas = new fabric.Canvas("canvas", {
backgroundColor: "black",
});
var rect = new fabric.Rect({
width: 100,
height: 85,
fill: "#ffefd5",
originX: "center",
originY: "center",
});
var text = new fabric.Text("TGIF", {
fontSize: 30,
originX: "center",
originY: "center",
});
var group = new fabric.Group([rect, text], {
left: 150,
top: 100,
angle: -10,
});
canvas.add(group);