How to set the position of Rectangle from top using FabricJS?


In this tutorial, we are going to set the position of Rectangle using FabricJS. The top property allows us to manipulate the position of the object. By default, the top position is relative to the object’s top.

Syntax

new fabric.Rect({ top: Number }: 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 the top is a property.

Options keys

  • top − This property accepts a Number which allows us to set the top position of the Rectangle.

Example 1

Default appearance of the Rectangle object

Let’s see a code example to understand how our rectangle object would appear when the top property is not used.

<!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>Default appearance of the Rectangle object</h2>
   <p>This is how our rectangle object appears when the top property is not used.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // Initiate a rectangle object
      var rect = new fabric.Rect({
         left: 55,
         width: 170,
         height: 70,
         fill: "black",
         padding: 9,
         stroke: "#483d8b",
         strokeWidth: 5,
      });

      // Add it to the canvas
      canvas.add(rect);
   </script>
</body>
</html>

Example 2

Passing the top property as key with a custom value

In this example, we are passing the top property as key, with a value of 90. This means that our rectangle object will be placed at a distance of 90px from the top.

<!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>Passing the top property as key with a custom value</h2>
   <p>Now the rectangle is placed at a distance of 90px from the top</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // Initiate a rectangle object
      var rect = new fabric.Rect({
         left: 55,
         top: 90,
         width: 170,
         height: 70,
         fill: "black",
         padding: 9,
         stroke: "#483d8b",
         strokeWidth: 5,
      });

      // Add it to the canvas
      canvas.add(rect);
   </script>
</body>
</html>

Updated on: 30-Jun-2022

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements