How to create a rectangle canvas using Fabric.js ?

In this article, we are going to create a canvas rectangle using FabricJS. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color or stroke width.

Approach: To make this possible we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rect provided by FabricJS and render the Rect instance on the Canvas instance as given in the example below.

Syntax:

fabric.Rect({
    width: number,
    height: number,
    fill: string,
    stroke: string,
    strokeWidth: int
}); 

Parameters: This function accepts five parameters as mentioned above and described below:

  • width: It specifies the width of rectangle.
  • height: It specifies the height of rectangle.
  • fill: It specifies the fill colour.
  • stroke: It specifies the stroke colour.
  • strokeWidth: It specifies the width of stroke.

Example: This example uses FabricJS to create simple editable canvas rectangle.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to create a rectangle
        canvas using Fabric.js ?
    </title>
      
    <!-- Adding the FabricJS library -->
    <script src=
    </script>
</head>
  
<body>
    <canvas id="canvas" width="600" height="200"
        style="border:1px solid #000000">
    </canvas>
      
    <script>
      
        // Initiate a Canvas instance
        var canvas = new fabric.Canvas("canvas");
  
        // Initiate a Rect instance
        var rectangle = new fabric.Rect({
            width: 200,
            height: 100,
            fill: '',
            stroke: 'green',
            strokeWidth: 3
        });
  
        // Render the Rect in canvas
        canvas.add(rectangle);
    </script>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.