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


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

Syntax

 viewportCenter(): fabric.Object 

Default appearance of the Line object

Example

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

Using the viewportCenter method

Example

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

Updated on: 20-Oct-2022

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements