FabricJS – How to center a Line object horizontally on a canvas?


In this tutorial, we are going to learn how to center a Line object horizontally on canvas using FabricJS. A Line element is one of the basic elements provided in FabricJS. It is used for creating straight lines. Because line elements are geometrically onedimensional and do not contain an interior, they are never filled. We can create a line object by creating an instance of fabric.Line, specifying the x and y coordinates of the line and adding it to the canvas. In order to center the line object horizontally on the canvas we use the centerH method.

Syntax

 centerH() 

Default appearance of the Line object

Example

Let’s see a code example to see how our line object looks when the centerH method is not used. In this case, the line object will not be centered horizontally on 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>Default appearance of the Line object</h2> <p>You can see that the line object has not been centered horizontally on the canvas</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 Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Add it to the canvas canvas.add(line); </script> </body> </html>

Using the centerH method

Example

In this example, we will see how by using the centerH method, we are able to place the line object exactly at the horizontal center of the canvas. In this case, the object is centered horizontally.

<!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>Using the centerH method</h2> <p> You can see that the line object has been centered horizontally on the canvas </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 Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Add it to the canvas canvas.add(line); // Using the centerH() method to center line object horizontally line.centerH(); </script> </body> </html>

Updated on: 20-Oct-2022

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements