Home >Web Front-end >JS Tutorial >How to create canvas using FabricJS?
In this article, we will create a canvas using FabricJS, but before that, let us understand what is canvas. For drawing graphics on web pages, we have a Web API called Canvas API. This API is fine for drawing basic shapes, but it becomes very difficult to add interactions or draw complex shapes. Hence, FabricJS emerged, a library built on top of the Canvas API. To use FabricJS, the first thing you need to do is create a FabricJS canvas.
new fabric.Canvas(element: HTMLElement|String, options: Object)
element − This parameter is
options (optional) − This parameter is an object that provides additional customization of the canvas. Using this parameter we can change different properties of the canvas like color, cursor, border width, etc.
Passing the id as a string
Let’s look at a code example of creating a canvas using FabricJS. Since FabricJS works on top of the Canvas API, we will create an HTML element using the
<!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>
Passing the element as HTMLElement
We can get the element using document.getElementById() while Instead of passing the id directly to the FabricJS API, then pass that element to the FabricJS API like this −
<!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>
The above is the detailed content of How to create canvas using FabricJS?. For more information, please follow other related articles on the PHP Chinese website!