How to add an object to a canvas using FabricJS?


In this article, we are going to how 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 −

<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
   <h2>How to add an object to a canvas in Fabric.js</h2>
   <p>Here you will get a circle as the object on the canvas</p>
   <canvas id="canvas"></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,
      }));
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

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>
   <h2>How to add an object to a canvas in Fabric.js</h2>
   <p>Here you will get a triangle as the object on the canvas</p>
   <canvas id="canvas"></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);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

Updated on: 20-May-2022

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements