Recently I had designed a client logo in Adobe Illustrator, and I wanted to place it in a HTML canvas in order to do various animations. Fabric seemed a good library to make this possible, as it has SVG loading (and saving) features built in. Fabric can load SVG data from a string or from a URL. SVG Mime Type
I had my SVG file stored in my website’s directory. Before I show you how to use fabric to load SVG files, here’s an important caveat. On my development machine, I am using IIS to serve my websites locally. I found that IIS does not, out of the box, serve .svg files, but serves a 404 error instead. The reason is that by default the .svg extension is not defined as a MIME type in IIS. To solve this, you must launch your IIS manager (inetmgr.exe), and in your default website find the “MIME types” section. Here, add “.svg” with MIME type “image/svg+xml”:
IIS should now serve .svg files normally. If you fail to do this, fabric will not be able to load .svg data from your website URL. I had earlier tried to rename my .svg files to .txt files, but fabric was unable to load these.
Creating a canvas
Here’s what you need to set up in order to use fabric. First, load the jQuery and Fabric libraries through a content delivery network:
Next, create a
<canvas> somewhere in your web page:
(I’ve added some style attributes to make the canvas more visible).
Loading the .svg file
This code loads an .svg file to your canvas:
This code has fabric load all paths from the SVG file, groups them, and adds them to the canvas.
You can also use this code, which allows you a little more control:
loadSVGFromURL method takes two function arguments. The second function (“options”) is called first on each object loaded, and here it is used to copy the ID from each item in the SVG file to the object created by fabric. All objects are placed in a variable “group”. The first function (“objects”) then copies all objects as a group to the canvas.