How to create a canvas using FabricJS?


In this article, we are going to create a canvas using FabricJS but before that let us understand what a canvas is. For drawing graphics on a webpage, we have a web API called Canvas API. This API is good for drawing basic shapes but adding interaction to it or drawing complex shapes becomes very difficult. Thus FabricJS comes into the picture which is a library built on top of the Canvas API. To use FabricJS, the first thing that needs to be done is to create a FabricJS Canvas.

Syntax

new fabric.Canvas(element: HTMLElement|String, options: Object)

Parameters

  • element − This parameter is the <canvas> element itself which can be derived using document.getElementById() or the id of the <canvas> element itself. The FabricJS canvas will be initialized on this element.

  • options (optional) − This parameter is an Object which provides additional customizations to our canvas. Using this parameter, we can change different properties of a canvas such as color, cursor, border width, and a lot of other properties.

Example 1

Passing the id as String

Let's see a code example to create a Canvas using FabricJS. Since FabricJS works on top of Canvas API, we will create an HTML element using <canvas> tag and give it an id. Further, we will pass that id to the FabricJS API so that it can initialize the FabricJS Canvas instance on the <canvas> tag.

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the FabricJS library -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js">
   </script>
</head>
<body>
   <h2>How to create a canvas using FabricJS</h2>
   <p>Select an area inside the canvas and you will get a highlighted section.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a Canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

Example 2

Passing the element as HTMLElement

Instead of passing the id directly to the FabricJS API, we can get the element using document.getElementById() and then pass that element to the FabricJS API as given below −

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the FabricJS library -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js">
   </script>
</head>
<body>
   <h2>How to create a canvas using FabricJS</h2>
   <p>Select an area inside the canvas and you will get a highlighted section.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a Canvas instance
      var element = document.getElementById('canvas');
      var canvas = new fabric.Canvas(element);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

Updated on: 27-Jun-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements