How to add an object to the canvas using FabricJS?

FabricJSJavascriptHTML5 Canvas

In this article, we are going to add an object to the canvas by using the add method. After creating our canvas, we can populate it with various objects available in FabricJS like fabric.Circle, fabric.Ellipse or fabric.Line, etc.

Syntax

canvas.add(object: fabric.Object);

Parameters

  • Object − This parameter is of type fabric.Object and holds the objects that we want to add to our canvas.

Example 1: Creating the instance of an object inside canvas.add()

Instead of creating the instance of an object first and then rendering it on the canvas by using the add() method, we can directly do so inside the add() method. Here is an example to illustrate that −

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>

<body>
   <div style="padding: 10px; font-weight: bold">
      How to add an object to the canvas using FabricJS
   </div>

   <canvas
      id="canvas"
      width="500"
      height="300"
      style="border: 2px solid #000000">
   </canvas>

   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.add(
         new fabric.Circle({
            radius: 40,
            fill: "#9370db",
            top: 100,
            left: 100,
         })
      );
   </script>
</body>
</html>

Output

Example 2: Creating an object and then adding it to the canvas

In this example, we will see how we can create a triangle object by using the fabric.Triangle class and add it to the canvas.

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
   <div style="padding: 10px; font-weight: bold">
      How to add an object to the canvas using FabricJS
   </div>

   <canvas id="canvas" width="500" height="300" style="border: 2px solid #000000">
</canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      // Creating an instance of the fabric.Triangle class
      var triangle = new fabric.Triangle({
         width: 60,
         height: 70,
         fill: "#87a96b",
         left: 30,
         top:20
      });
      // Adding it to the canvas
      canvas.add(triangle);
   </script>
</body>
</html>

Output

raja
Updated on 24-Mar-2022 08:13:29

Advertisements