How to group multiple Polylines into a single object using FabricJS?

We can create a Polyline object by creating an instance of fabric.Polyline. A polyline object can be characterised by a set of connected straight-line segments. Since it is one of the basic elements of FabricJS, we can also easily customize it by applying properties like angle, opacity, etc. For grouping multiple Polyline objects, we can use the toGroup() method.

Syntax

toGroup(): Fabric.Group

Example 1: Creating an Instance of fabric.Polyline() and Adding it to our Canvas

Before seeing how we can group multiple objects into one, let?s see a code example of how we can add a polyline object to our canvas. The only required parameter is the points Array whereas the second argument is the optional options object.



   
   


   

Creating an instance of fabric.Polyline() and adding it to our canvas

You can see that the polyline object has been added

Example 2: Grouping all the Polylines using One Click

In this example, we will have a button on clicking which all the Polylines will be grouped into a single object. Thus moving that object will move all the Polylines and it will behave as a single object as you resize or skew too. We will create a function which gets all the objects in the canvas and groups them into a single object.



   
   


   

Grouping all the Polyline objects using one click

Click on the `Group` Button to group all the Polyline objects in the canvas

Updated on: 2023-02-16T16:26:16+05:30

675 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements