How to add shadow to a Rectangle using FabricJS?

In this tutorial, we are going to learn how to add a shadow to a Rectangle using FabricJS. Rectangle is one of the various shapes provided by FabricJS. In order to create a rectangle, we will have to create an instance of fabric.Rect class and add it to the canvas.

Our rectangle object can be customized in various ways like changing its dimensions, adding a background color, or even adding a shadow to it. We can add a shadow to the rectangle by using the shadow property.

Syntax

new fabric.Rect({ shadow : fabric.Shadow }: Object)

Parameters

  • Options (optional) ? This parameter is an Object which provides additional customizations to our rectangle. Using this parameter, properties such as colour, cursor, stroke width, and a lot of other properties can be changed related to the object of which shadow is a property.

Options Keys

  • shadow ? This property accepts a fabric.Shadow object which allows us to add a shadow to our Rectangle object. For example, in order to add a shadow to our Rectangle object, we need to create a new instance of fabric.Shadow and then assign that instance to the shadow property.

Example 1

Passing the shadow object to the shadow property

Let?s see a code example to understand how we can assign the shadow property a value such that a shadow will be added to our rectangle object. First, we need to make a new instance of fabric.Shadow and then assign that instance to our shadow property.



   
   


   

Passing the shadow object to the shadow property

   

You can see that an orange shadow has been added to the rectangle

       

Example 2

Passing an "rgba" value to the shadow object

We can also adjust the shadow and give it a blurred-out appearance by assigning it an "rgba" value which stands for red, green, blue and alpha. Alpha determines the opacity of the colour.



   
   


   

Passing an rgba value to the shadow object

   

You can see the new shadow created using rgba value

       
Updated on: 2022-06-28T12:16:01+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements