Fabric js- A Comprehensive Guide
API Tech Talk

Fabric JS – A Comprehensive Guide

Fabric JS is a common term mostly heard from those developers who are working with HTML5 Canvas. So ever wondered why this has gained so much prominence in cases where dealing with Canvas-related implementations? The answer is because of its well-defined apis for implementing simple/complex solutions and the excellent documentation provided by the developers. 

In this blog, you will get to know more about what Fabric JS is and all things it can do in the coming sections.

What is Fabric JS?

Fabric JS is an HTML5 Canvas library which will help you create graphics of different varieties and modify their properties with more ease than the native HTML5 Canvas API.

Why Fabric?

HTML5 Canvas helps you to create amazing graphics on the webpage but the API it provides for building these graphics is disappointingly very low level. Because of this, the manipulations to the developed graphics or adding mode interactivity to the graphics is a bit difficult. This is where the fabric js library comes to help, Fabric JS is a library built over the HTML5 Canvas implementations which have created well-defined API and proper documentation for the simple/complex graphics implementation. 

Fabric JS provides a lot of code abstraction where the developer just needs to make use of these APIs to create/manipulate their graphics. Moreover, all the background code is handled by the library.

Next, let’s dive into and see how to use Fabric js to draw a rectangle.

var canvas = new fabric.Canvas(‘c’);

 

// create a rectangle with angle=45

var rect = new fabric.Rect({

  left: 100,

  top: 100,

  fill: ‘red’,

  width: 20,

  height: 20,

angle: 45

});

canvas.add(rect);

The above code will display a rectangle for you on the screen. From the example above, it is clear that fabric js operates on objects.

First, it gets the canvas element ‘c’ as an object. After that, it creates a rectangle object with some properties of a rectangle and then this object is added to the canvas. This in turn, results in a rectangle.

fabric js

Other than rectangles, Fabric js provides ready API for Circle, Ellipses, Polygon, Polyline, Triangle and Line.

Manipulating Objects

Now, you might clear on how to create different types of object graphics using fabric js.

Next, let’s assume a scenario where you want to change the properties of the graphics object on the fly. For eg. Change the color of the rectangle based on some condition.

Using the native canvas implementation, the only way to accomplish this is to destroy the current object and redraw the same object with the specified color. So, eventually we need to rewrite the whole thing again. 

However, if you are working with fabric js, then this scenario is efficiently handled by the library as a background process. You just need to call the Set() property to specify your changes and the object will be rerendered.

Interactivity

Fabric js provides you with the excellent support of object interactivity which means once a graphic is created you can interact with the object with the mouse or keyboard. Apart from this, you can even freely draw different images over the canvas. 

Fabric js provides fast and smooth interactivity for any complex drawings or shapes.

There is a wide variety of parameters that accepts mostly boolean values which help you set what type of interaction you need for the application.

See a few examples below.

lockMovementX / lockMovementX: Property accepts boolean values to set the top or bottom interaction.

Selection: True/false will make the object selectable or not.

lockScalingX / lockScalingY: Sets the interaction to resize the object. 

lock rotation: Lock rotation enables/disables the rotation of the object.

fabric js2fabric js1

Animations

Fabric JS also supports adding animations to your graphics. While discussing the manipulation of objects we have used the object.set() method to simply set different properties to our graphics and to re-render the same without any delay. It was so easy to handle with respect to our native canvas code. 

Similarly, with the animations too. Fabric js provides you with direct methods to apply various built-in animations as well as create your own. Fabric JS uses the object.animate() method to apply the animation to our graphic.

rect.animate(‘angle’, 45, {

  onChange: canvas.renderAll.bind(canvas)

});

Let’s assume that we have a rectangle created and displayed in our canvas. The object name for that rectangle is ‘rect’. Now, to add a small animation to rotate it to a specified angle after its initial render, we can use the above code snippet.

The animate method accepts the type of property to be applied which is the angle here and its value. So while executing the code the object will be rotated by 45 degrees.

Now, let’s look at some of the properties accepted by the animate method.

From: From property defines the starting value of the animation. This is actually an optional property which needs to be added only if we want to override the existing value at the start of the animation.

Duration: The duration property as the name suggests sets the duration of the animation. It specifies what time the animation should extend. The default value for the duration is 500ms and is automatically added if we don’t specify any value.

OnComplete: Oncomplete is nothing but a callback function. There may be some scenarios in our program where we need to execute a piece of code or implement some logic once the animation is completed. The onComplete callback method helps in this situation to trigger when the animation finishes.

Easing: Easing property of the animation specifies the type of animation to be used in the canvas. The easing has some fixed options which apply to the animating object on its entry to the canvas. This includes easeInCubic, easeOutCubic, easeInElastic, easeOutElastic, easeInBounce, and easeOutExpo.

Image Filters

Image Filters in Fabric JS are used to apply some filters over the images. You can overlay some built-in filters over the graphics or you can create your own filters and apply them to your canvas images.

img.filters.push(new fabric.Image.filters.Grayscale());

The above code overlays a grayscale filter over your image defined with the ‘img’ object

You can create your own filters by using the fabric createClass() method.

fabric.Image.filters.Redify = fabric.util.createClass(fabric.Image.filters.BaseFilter, {

  type: ‘Redify’,

  fragmentSource: ‘precision highp float;\n’ +

    ‘uniform sampler2D uTexture;\n’ +

    ‘varying vec2 vTexCoord;\n’ +

    ‘void main() {\n’ +

      ‘vec4 color = texture2D(uTexture, vTexCoord);\n’ +

      ‘color.g = 0.0;\n’ +

      ‘color.b = 0.0;\n’ +

      ‘gl_FragColor = color;\n’ +

    ‘}’,

  applyTo2d: function(options) {

    var imageData = options.imageData,

        data = imageData.data, i, len = data.length;

    for (i = 0; i < len; i += 4) {

      data[i + 1] = 0;

      data[i + 2] = 0;

    }

  }

});

fabric.Image.filters.Redify.fromObject = fabric.Image.filters.BaseFilter.fromObject;

The above code snippet will create a user-defined filter called redify, which will apply a red overlay over the image.

Serialization / Deserialization

Let’s assume a situation where we created beautiful graphics in our web application but what is its use if we are not able to save it on the server and load them to the webpage in future to see it again? 

Here is where the serialization and deserialization function of fabric helps you out. 

  • Serialization helps you save your graphics into any server using any rest API in an object or SVG format. 
  • Deserialization helps you to decode the serialized and saved data and re render it in the web application.

rect.toObject = (function(toObject) {

  return function() {

    return fabric.util.object.extend(toObject.call(this), {

      name: this.name

    });

  };

})(rect.toObject);

The above code will convert the graphic to an object and you can save it to any server.

Similar to the toObject() method, there is also toSvg() available which converts the graphic to svg code.

Once saved to the server, we can use the loadFromJson() method or the loadFromSvgString() method to deserialize the graphics code and rerender it again.

What More ???

The above-mentioned features of fabric js are not the only features available there. In fact, these are some of the basic concepts of fabric js, which a developer can extend to any level for development purposes. Mostly a combination of multiple features is used to implement various projects.

Since fabric js opens a wide range of features to interact and play with graphics. Many leading companies have shown interest in it and it is being used in their daily running projects. 

As I mentioned earlier fabric js is also an open-source library which accepts contributions from skilled developers all over the globe. So, it can be said that this library is well-maintained and is always emerging with new enhancements. 

Perfomatix | Product Engineering Services Company