How to create a Rectangle with background colour using FabricJS?

In this tutorial, we are going to create a Rectangle with background colour 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.

The backgroundColor property allows us to assign a colour to our object?s background. It is the colour of the container where the rectangle lives and is rectangular in shape for the rectangle.

Syntax

new fabric.Rect({ backgroundColor: String }: 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 Rectangle of which backgroundColor is a property.

Options Keys

  • backgroundColor ? This property accepts a value of type String which will determine the background colour.

Example 1

Passing backgroundColor property as key with a hexadecimal value

Let?s see a code example to assign a background colour to our Rectangle object using a hexadecimal value. In this example, we have used the hex colour code #ffb347 which is an orange colour.



   
   


   

Passing backgroundColor property as key with a hexadecimal value

   

You can see the new background colour on the rectangle

       

Example 2

Passing backgroundColor property as key with an RGBA value

We can use an RGBA value, instead of a hexadecimal colour code. The alpha parameter specifies the opacity of a colour. In this example, we have used the rgba value (207,16,32,0.9) which is the colour red with 0.9 opacity.



   
   


   

Passing backgroundColor property as key with an RGBA value

   

You can see the new background colour on the rectangle

       
Updated on: 2022-06-28T12:38:09+05:30

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements