How to make a polygon object react to the mouse events using FabricJS?

We can create a Polygon object by creating an instance of fabric.Polygon. A polygon object can be characterized by any closed shape consisting of 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. We use the mouseup and mousedown events to demonstrate how a polygon object reacts to the mouse events triggered by a user.

Syntax

polygon.on("mouseup", callbackFunction);
polygon.on("mousedown", callbackFunction);

Example 1: Displaying how the Object Reacts to the mouseup Event

Let?s see a code example of how the polygon object reacts when the mouseup event is triggered. A mouseup event occurs when the user releases the left mouse button. Here, as soon as the mouseup event is triggered, the stroke width changes to 33.



   
   


   

Displaying how the object reacts to the mouseup event

You can select the object and release the left mouse button to see that the stroke width has changed

Example 2: Displaying how the Object Reacts to the mousedown Event

Let?s see a code example of how the polygon object reacts when the mousedown event is triggered. A mousedown event occurs when a user presses a button down. Here, we can see that the object reacts to the mousedown event by changing its stroke width from 33 to 2.



   
   


   

Displaying how the object reacts to the mousedown event

You can press the left mouse button to trigger the mousedown event to see that the stroke width has changed

Conclusion

In this tutorial, we used two simple examples to demonstrate how you can make a polygon object react to the mouse events using FabricJS.

Updated on: 2023-01-02T15:52:11+05:30

816 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements