Fabric.JS Objects And Shapes Guide

Dinesh Rawat
5 min readMay 12, 2023

A powerful tool that allows developers to create complex shapes, graphics, and animations using HTML5’s canvas element, Fabric.js is an open-source JavaScript library for creating interactive and high-quality web graphics. By simplifying the creation and manipulation of graphical objects, Fabric.js allows developers to build creative and dynamic websites.

Demo project structure

Prior to delving into Fabric.js specifics, grasping the demo project structure holds significance. Upon downloading Fabric.js, a folder labeled “demo” will be available, encompassing diverse examples and projects showcasing Fabric.js functionalities. The demo folder is organized in a manner that facilitates comprehension and customization of projects to suit individual requirements.

Canvas initializing

In order to utilize Fabric.js, it is essential to have a canvas element present on your webpage. The initial step to set up a Fabric.js canvas involves creating an instance of the fabric.Canvas class. This class serves as the controller for the canvas element and handles the management of graphical objects within it.

To initialize a canvas, you can employ the following code snippet:

var canvas = new fabric.Canvas('canvasId');

The code snippet uses “canvasId” as the identifier for the canvas element present on your webpage. Once the canvas is initialized, you gain the ability to create and manipulate graphical objects.

Fabric.js is a powerful tool for developing interactive and imaginative web applications. Its extensive capabilities enable the creation of intricate shapes, graphics, and animations with relative simplicity. By comprehending the demo project structure, canvas initialization, and other features and functions of Fabric.js, you can elevate your web development projects to new heights.

Drawing Objects with Fabric.js

Fabric.js is a robust library renowned for its capacity to render diverse shapes and objects. The following section will guide you through the process of drawing multiple objects using Fabric.js.

1. Drawing Rectangles and Ellipses

Creating rectangles and ellipses is a simple task with Fabric.js. To draw a rectangle, utilize the fabric.Rect class and specify attributes like height, width, fill color, border color, and border width. Similarly, for drawing an ellipse, employ the fabric.Ellipse class and provide attributes such as radius, fill color, border color, and border width.

Here’s an example code illustrating the process of drawing a rectangle and an ellipse using Fabric.js:

// Create a rectangle
var rect = new fabric.Rect({
left: 100,
top: 100,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 2
});

// Create an ellipse
var ellipse = new fabric.Ellipse({
left: 250,
top: 100,
rx: 50,
ry: 25,
fill: 'blue',
stroke: 'black',
strokeWidth: 2
});

// Add both objects to the canvas
canvas.add(rect, ellipse);

2. Free-hand Drawing

Fabric.js provides the capability to draw free-hand shapes using the fabric.Path class. Drawing a free-hand shape requires providing an array of points that define the path. The points determine the trajectory of the drawn shape.

Here is an example code showcasing how to draw a free-hand shape using Fabric.js:

// Create a free-hand path
var path = new fabric.Path('M 0 0');

// Set the stroke color and width

path.set({
stroke: 'green',
strokeWidth: 5
});

// Add the path to the canvas
canvas.add(path);


// Listen for mouse down event to start drawing the path
canvas.on('mouse:down', function(event) {
var pointer = canvas.getPointer(event.e);
path.path[0][1] = pointer.x;
path.path[0][2] = pointer.y;

canvas.renderAll();
});


// Listen for mouse move event to continue drawing the path
canvas.on('mouse:move', function(event) {
if (!path.path.length) return;
var pointer = canvas.getPointer(event.e);

path.path.push(['L', pointer.x, pointer.y]);
canvas.renderAll();
});


// Listen for mouse up event to stop drawing the path
canvas.on('mouse:up', function(event) {
path.setCoords();
canvas.renderAll();
});

3. Line-dashed Line

Fabric.js offers the capability to draw dashed lines through the fabric.Line class. To create a dashed line, you must provide the strokeDashArray attribute, which is an array of numbers indicating the lengths of the dashes and gaps in the line.

The following code showcases the process of drawing a dashed line using Fabric.js:

// Create a dashed line
var line = new fabric.Line([50, 50, 250, 50], {
stroke: 'black',
strokeWidth: 2,
strokeDashArray: [5, 2]
});

// Add the line to the canvas
canvas.add(line);

4. Polygon

Fabric.js allows you to draw polygons as well. To create a polygon, you must supply the “points” attribute, which is an array containing the x and y coordinates of each point in the polygon. The code snippet below showcases how to draw a polygon using Fabric.js:

var polygon = new fabric.Polygon([{
x: 150,
y: 50
}, {
x: 225,
y: 150
}, {
x: 150,
y: 250
}, {
x: 75,
y: 150
}], {
fill: 'orange',
stroke: 'black',
strokeWidth: 5
})

Using Fabric.js in Complex Shapes

Fabric.js is a popular and potent JavaScript library extensively utilized for graphic and animation creation and manipulation on the web. While drawing fundamental shapes and objects with Fabric.js is relatively uncomplicated, users can fully unleash its capabilities by harnessing its advanced features to craft intricate shapes and designs. In this section, we will delve into the utilization of Fabric.js to construct complex shapes by combining and manipulating objects, performing rotations and scaling, and incorporating text and additional elements.

Read more about complex shapes in Fabric.js.

Tips for Optimizing Fabric.js Performance

Besides debugging and troubleshooting, optimizing Fabric.js performance is crucial for achieving maximum efficiency and speed. Here are some tips to enhance Fabric.js performance:

  1. Utilize caching: Fabric.js provides a caching mechanism to accelerate object rendering and manipulation. By caching frequently used objects and settings, you can reduce processing power requirements.
  2. Preload images: Preloading images before their usage in Fabric.js projects helps reduce load times and enhances overall performance.
  3. Implement object pooling: Object pooling involves reusing existing objects instead of creating new ones. This technique reduces memory consumption in Fabric.js projects.
  4. Minimize DOM interactions: DOM interactions can be slow and resource-intensive. Minimize the impact by batching and throttling interactions to reduce the number required.
  5. Optimize animations: Animations can consume significant resources. Optimize them by utilizing techniques like requestAnimationFrame and limiting the number of simultaneous animations.

By applying these tips and techniques, you can ensure a smooth and efficient execution of your Fabric.js project, minimizing errors and maximizing performance.

Read more about complex shapes in Fabric.js.

--

--

Dinesh Rawat

Seasoned software engineer, Content creator, Helping teams achieve their goals. https://www.linkedin.com/in/dinesh-rawat/