De-serialize SVG to canvas using FabricJS

Mandev
4 min readDec 8, 2022

--

There are three important words in the above title, let’s break them down one by one:

  1. Deserialize — When we extract a data structure from a series of bytes, the process is called deserialization. In other words, a lower level format is transformed into a readable object.
  2. SVG — It is a language based on XML that describes 2D vectors on the web. It stands for Scalable Vector Graphics and is used to create interactive documents, dynamic changes and some really cool animations as well.
  3. Canvas — The HTML5 canvas allows us to draw, add, animate, scale or manipulate objects.

Read: Serialization

Suggestion: How to create a Canvas using FabricJS

Target: Loading an SVG file into the Canvas using FabricJS

We can load an SVG file into the canvas using two methods. They are:-

  1. fabric.loadSVGFromURL — We need to pass the URL of the SVG file or design that we want to use as the first argument.
  2. fabric.loadSVGFromString — Loads the svg file from the string representation.

Both of these are Static Methods that are called on the fabric object rather than on a canvas instance.

I used this website to download free svg files

How to load SVG from a String

Step 1: Download the SVG cut file and unzip it.

Step 2: Copy the .svg file into the folder where you have your index.html file.

Step 3: As soon as you open the .svg file in VS Code, you will see SVG contents starting with <svg> element container.

Step 4: Copy all of that and paste it in your index.html file like so:

Paste the SVG file right below the HTML <canvas> element

Step 5: In the <style> tag of the svg file, set display: none.

Step 6: Fetch the svg element using the getElementByTagName and serialize it into a string by using the serializeToString() method.

  • We are basically converting the svg HTML element into String format since fabric.loadSVGFromString accepts only the String representation.

Step 7: Create a canvas instance and use the loadSVGFromString() method to display the svg file on the canvas. This method accepts a function in the second parameter. Therefore we can change the properties of the svg like scaling, rotating, changing its top or left values etc.

  • Here’s the JS file for your better understanding:
      var svgElement = document.body.getElementsByTagName("svg")[0];

// The XMLSerializer interface provides serializeToString() method
var serializer = new XMLSerializer();

// Serializing the svg element and return that as a String
var svgString = serializer.serializeToString(svgElement);

// Creating the Canvas instance
var canvas = new fabric.Canvas("canvas", {
backgroundColor: "#fe5a1d",
isDrawingMode: false,
freeDrawingCursor: "default",
});

// Loading the SVG using loadSVGFromString() method
var path = fabric.loadSVGFromString(
svgString,
function (objects, options) {
var obj = fabric.util.groupSVGElements(objects, options);
obj.set({ left: 20, top: 20, scaleX: 0.5, scaleY: 0.5 });
obj.setCoords();

// Adding it to the canvas
canvas.add(obj);
canvas.renderAll();
}
);
Loading an SVG file from its String representation

How to Load SVG from URL

Step 1: Create a Folder where you want to store your FabricJS files. I named mine as Fabric-Demo.

Step 2: Open the terminal using (Ctrl+~) and enter the following command:

npm create vite@latest

We are setting up our local server by using Vite so that we don’t run into CORS issues while working with svg URL.

Step 3: Add FabricJS by using this command in your terminal:

npm i fabric

Step 4: Remove all the boilerplate code from the main.js, index.html and style.css files.

Step 5: Import the FabricJS library in your main.js file like so:

import { fabric } from "fabric";

Step 6: Create a script tag in your index.html file and set its type as “module”. Also, use the src attribute to set the location of main.js.

Step 7: Use loadSVGFromURL and pass the URL as the first argument. In the second argument, use a function to set the properties.

Our main.js file should look like this:

import { fabric } from "fabric";

// Creating the Canvas instance
var canvas = new fabric.Canvas("canvas", {
backgroundColor: "#f0fff0",
isDrawingMode: false,
freeDrawingCursor: "crosshair",
});

fabric.loadSVGFromURL(
"assets/Christmas-Time .svg",
function (objects, options) {
var christmasSVG = fabric.util.groupSVGElements(objects, options);
christmasSVG.set({ left: 40, top: 5, scaleX: 0.7, scaleY: 0.7 });
canvas.add(christmasSVG);
canvas.calcOffset();
canvas.renderAll();
}
);
This is how index.html should appear
Loading an SVG file into the file using a URL

Useless Outro

This is the final article of my FabricJS series. I feel so happy for some reason as if I have finally added something onto this world.

I know these articles aren’t perfect and even if you don’t like it, I am grateful that you gave it a chance and read it.

2022 will be over in 22 days huh… didn’t see that coming. I feel like the only thing I achieved this year was not giving up on doing laundry.

But I hope yours was much better than that (*^-^*)So, wrap yourself in a cozy blanket, keep your coffee on the sidetable — not near the keyboard pleaseeee ╯°□°)╯︵ ┻━┻ and keep coding!

See ya until next time!

--

--