Home >Web Front-end >JS Tutorial >How to create a canvas with classes using FabricJS?
In this article, we will see how to create a canvas with a class using the containerClass property. In order to access the native HTML canvas element, we can add a wrapper class on it. This class allows us to control elements to add interactivity or styling as per requirement.
new fabric.Canvas(element: HTMLElement|String, { containerClass: String}: Object)
Element - This parameter is
Options (optional) - This parameter is an object that provides additional customization of our canvas. Use this parameter to change the color, cursor, border width, and many other properties related to the canvas. containerClass is one of them, which will help us add wrapper classes to the canvas.
The following content example demonstrates how to create a Canvas using the containerClass attribute and then inspect the HTML DOM to see if the class has been added.
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>How to create a canvas with a class using FabricJS?</h2> <p>Here we have used the containerClass property.</p> <canvas id="canvas"> </canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas", { // Name of the wrapper class to be used on the canvas containerClass: "className", }); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); </script> </body> </html>
Now open Development Tools → Elements tab. Here you will notice that the class name we provided is used as the name of the class.
Let’s look at a code example that creates a Canvas using the containerClass property and then uses that class to add CSS to the canvas style.
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> <style> .demo { background-color: #ffe4e1; } </style> </head> <body> <h2> Creating a canvas with a class using FabricJS </h2> <p> Here we have set a wrapper class and then used it to style our canvas. </p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas", { // Name of the wrapper class to be used on the canvas containerClass: "demo", }); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); </script> </body> </html>
The above is the detailed content of How to create a canvas with classes using FabricJS?. For more information, please follow other related articles on the PHP Chinese website!