How to get the SVG representation of a Line using FabricJS?


In this article, we are going to learn about how to get the SVG representation of a Line 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 get the SVG representation of a Line object, we use the _toSVG method.

Syntax

 _toSVG(): Array 

Without using _toSVG method

Example

Let’s see a code example to see the logged output when the _toSVG method is not used. The _toSVG method returns an array of strings with a specific svg representation of the instance. However, since we have not used the _toSVG method, we will not be able to see the array of strings in the console. The Line object’s default value has been logged to illustrate that.

<!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>Without using _toSVG 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([70, 100, 150, 200], { stroke: "blue", }); // Add it to the canvas canvas.add(line); // Console logging the Line object console.log("The Line object is as follows: ", line); </script> </body> </html>

Using the _toSVG method

Example

In this example we have used the _toSVG method to obtain an array of strings containing the svg representation of the object.

<!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 _toSVG method</h2> <p> You can open console from dev tools and see that the logged output contains an array of strings containing the svg representation of the Line object </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([70, 100, 150, 200], { stroke: "blue", }); // Add it to the canvas canvas.add(line); // Using the _toSVG method console.log( "The svg representation of the Line object is as follows: ", line._toSVG() ); </script> </body> </html>

Updated on: 21-Oct-2022

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements