In this article, we will use the add method to add objects to the canvas. After creating the canvas, we can fill it with various objects available in FabricJS, such as fabric.Circle, fabric.Ellipse or fabric.Line, etc.
canvas.add(object: fabric.Object);
Object - The type of this parameter is fabric.Object and Saving the object
Instead of creating an instance of the object first get it and then use add( ) method to render it onto the canvas, we can do this directly in the add() method. Here is an example to illustrate -
<!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> <div style="padding: 10px; font-weight: bold"> How to add an object to the canvas using FabricJS </div> <canvas id="canvas" width="500" height="300" style="border: 2px solid #000000"> </canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.add( new fabric.Circle({ radius: 40, fill: "#9370db", top: 100, left: 100, }) ); </script> </body> </html>
In In this example, we will see how to create a triangle object using the Fabric.Triangle class and add it to the canvas.
<!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> <div style="padding: 10px; font-weight: bold"> How to add an object to the canvas using FabricJS </div> <canvas id="canvas" width="500" height="300" style="border: 2px solid #000000"> </canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); // Creating an instance of the fabric.Triangle class var triangle = new fabric.Triangle({ width: 60, height: 70, fill: "#87a96b", left: 30, top:20 }); // Adding it to the canvas canvas.add(triangle); </script> </body> </html>
The above is the detailed content of How to add objects to canvas using FabricJS?. For more information, please follow other related articles on the PHP Chinese website!