Home > Article > Web Front-end > How to get the coordinates of a Line object using FabricJS?
In this tutorial, we will show how to get the coordinates of a line using FabricJS. Line element is one of the basic elements provided in FabricJS. It is used to create straight lines. Since line elements are geometrically one-dimensional and contain no interiors, 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. To get the coordinates of a Line object, we use the getCoords method.
getCoords(): Array
Let’s look at a code example to see getCoords Used for the output recorded when the method is executed. getCoords The method returns the coordinates of the upper left corner, upper right corner, lower right corner and lower left corner of Line in array format.
<!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 getCoords method</h2> <p>You can open console from dev tools and see the logged output</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([50, 100, 310, 100], { stroke: "blue", strokeWidth: 10, }); // Add it to the canvas canvas.add(line); // Using getCoords method console.log("The coordinates are: ", line.getCoords()); </script> </body> </html>
In this example, we use the getCoords method to get values with different starting and The coordinate of the Line instance that ends the coordinate. We can see that the recorded output is: (100, 40), (220, 40), (220,120), (100,120), which are the coordinates of the upper left corner, upper right corner, lower right corner and lower left corner of the line respectively.
<!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 getCoords method for a slant line</h2> <p>You can open console from dev tools and see the logged output</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 getCoords method console.log("The coordinates are: ", line.getCoords()); </script> </body> </html>
The above is the detailed content of How to get the coordinates of a Line object using FabricJS?. For more information, please follow other related articles on the PHP Chinese website!