paint-brush
Simplifying Object Manipulation: Grouping and Ungrouping Fabric.js Objectsby@dineshrawat
2,472 reads
2,472 reads

Simplifying Object Manipulation: Grouping and Ungrouping Fabric.js Objects

by Dinesh RawatJune 1st, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Fabric.js object groups simplify object manipulation by allowing you to move, modify, and apply property changes to multiple objects simultaneously. Ideal for web developers looking to enhance productivity and efficiency in canvas-based applications.
featured image - Simplifying Object Manipulation: Grouping and Ungrouping Fabric.js Objects
Dinesh Rawat HackerNoon profile picture

When we hear the word "group," we often think of various associations, from social circles to musical bands or even a gathering of animals.


A Fabric.js group is a collection of objects that are clustered together.


These groups serve multiple purposes, such as moving and modifying objects collectively or applying property changes uniformly across multiple objects.


In this blog post, we will explore how to create object groups using Fabric.js, empowering you to streamline your object manipulation and modification tasks.

Why Use Object Groups in Fabric.js:

Object groups offer several advantages and functionalities, including:


  1. Moving Multiple Objects Together: With object groups, you can conveniently move multiple objects as a single unit, simplifying the positioning and arrangement of complex scenes.
  2. Modifying Objects as a Group: By grouping objects, you can apply modifications uniformly across the entire group, saving time and effort when making changes to related objects.
  3. Applying Property Changes: Object groups enable simultaneous property changes, allowing you to apply transformations like skewing, scaling, fill color, stroke, and more to multiple objects at once.


Creating Object Groups in Fabric.js:

To create an object group in Fabric.js, we utilize the fabric.Group constructor. Let's take a closer look at its syntax and usage:


Syntax:


new fabric.Group(objects: Object, 
                  options(optional): Object, 
                  isAlreadyGrouped(optional): Boolean);


  • The objects parameter accepts an array of objects that we want to group together.
  • Optional options can be passed as an object, allowing customization of group properties like position and angle.
  • The isAlreadyGrouped parameter is used to indicate if the provided objects are already grouped.

Creating a Basic Object Group:

Follow these steps to create a basic object group:


  1. You can group shapes, images, or text elements by creating individual objects.
  2. Pass these objects as an array to the fabric.Group constructor.


Example:


var circle = new fabric.Circle({ radius: 30, fill: "#FF0000" });
var image = new fabric.Image(...);
var text = new fabric.Text("Hello", ...);

var group = new fabric.Group([circle, image, text]);
canvas.add(group);


A circle, an image, and a text element are combined in the above example. The group variable represents the newly created object group, which is then added to the canvas.

Customizing Object Groups:

You can further customize object groups by providing optional properties to the options object parameter. These properties allow you to define the group's position, rotation angle, and other visual attributes.


Example:



var group = new fabric.Group([circle, image, text], {
  left: 70,
  top: 94,
  angle: -10,
});


In the above example, we set theleft and top properties to position the group on the canvas. Additionally, we specify an angle to rotate the entire group.


Creating a Group of Two Objects:

Creating a group of two objects follows a similar approach. However, we need to ensure proper alignment within the group by setting the originX and originY properties to "center" for each object.


Example:


var rect = new fabric.Rect({
    width: 100,
    height: 85,
    fill: "#FFC0CB",
    originX: "center",
    originY: "center"
});
var text = new fabric.Text("Hello world@", {
    fontSize: 30,
    originX: "center",
    originY: "center"
});

var group = new fabric.Group([rect, text], {
    left: 150,
    top: 100,
    angle: -10
});
canvas.add(group);


In the above example, we create a group of a rectangle and text element. By specifying the originX and originY properties as "center" for each object, we ensure they are properly centered within the group.


Ungrouping Fabric.js Objects

In addition to creating groups of objects in Fabric.js, you also have the ability to ungroup them when needed. Ungrouping objects allows you to restore their individual properties and manipulate them independently. Let's explore how to ungroup objects using Fabric.js with an example.

Example of Ungrouping Objects:

You want to ungroup a group of objects and treat them separately. Consider a group consisting of two rectangles and a text element.


We will demonstrate how to ungroup them using Fabric.js.


var canvas = new fabric.Canvas("canvas");

// Create the rectangles
var rect1 = new fabric.Rect({
  width: 100,
  height: 50,
  fill: "blue",
  left: 50,
  top: 50,
});

var rect2 = new fabric.Rect({
  width: 100,
  height: 50,
  fill: "red",
  left: 200,
  top: 50,
});

// Create the text element
var text = new fabric.Text("Hello", {
  fontSize: 20,
  fill: "white",
  left: 120,
  top: 60,
});

// Group the objects
var group = new fabric.Group([rect1, rect2, text], {
  left: 100,
  top: 100,
});

canvas.add(group);

// Ungroup the objects
var activeObj = canvas.getActiveObject();
var activegroup = activeObj.toGroup();
var objectsInGroup = activegroup.getObjects();

activegroup.clone(function(newgroup) {
    canvas.remove(activegroup);
    objectsInGroup.forEach(function(object) {
        canvas.remove(object);  
    });
    canvas.add(newgroup);
    canvas.setActiveObject(newgroup);
    canvas.requestRenderAll();
});

canvas.renderAll();


In the code above, we assume that canvas is the Fabric.js canvas object.


First, we retrieve the active object from the canvas using getActiveObject(). We then convert the active object into a group using the toGroup() method, and store it in the activegroup variable.

A list of objects within the group is obtained using the getObjects() method and stored in the objectsInGroup variable.


A clone of the activegroup is then created using the clone() method. Inside the callback function of clone(), we remove the activegroup from the canvas using remove(activegroup).


We iterate over the objectsInGroup array and remove each individual object from the canvas using remove(object).


After removing the group and its objects, we add the cloned group back to the canvas using add(newgroup).


Finally, we set the newgroup as the active object on the canvas using setActiveObject(newgroup), and request the canvas to render the changes using requestRenderAll(). By executing this code, you will ungroup the objects and have them restored as separate entities on the canvas.

Conclusion

Mastering object grouping in Fabric.js empowers you to simplify object manipulation and modification tasks. By creating object groups, you can move, modify, and apply property changes to multiple objects simultaneously, enhancing your productivity and efficiency.


Whether you're working with complex scenes or need to apply uniform transformations, object groups in Fabric.js are a valuable tool in your development arsenal. Start leveraging the power of object grouping in Fabric.js and take your canvas-based applications to the next level.