FabricJS – How to center a Line object vertically on the current viewport of canvas?


In this tutorial, we are going to learn about how to center a Line object vertically on current viewport of 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 one-dimensional 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 a Line object vertically on current viewport of canvas, we use the viewportCenterV method.

Syntax

 viewportCenterV(): fabric.Object 

Default appearance of the Line object

Example

Let’s see a code example to see how our Line object looks when the viewportCenterV method is not used. In this case, the line object will not be centered vertically 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 is not centered vertically with respect to the current viewport of 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: 6, }); // Add it to the canvas canvas.add(line); </script> </body> </html>

Using the viewportCenterV method

Example

Let’s see a code example to see how the line object looks like when the viewportCenterV method is used. In this case, our line object will be centered vertically with respect to the current viewport of 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>Using the viewportCenterV method</h2> <p> You can see that the line object is centered vertically with respect to the current viewport of 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: 6, }); // Add it to the canvas canvas.add(line); // Using the viewportCenterV method line.viewportCenterV(); </script> </body> </html>

Updated on: 20-Oct-2022

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements