Home >Web Front-end >JS Tutorial >How to add objects to canvas using FabricJS?

How to add objects to canvas using FabricJS?

WBOY
WBOYforward
2023-09-06 16:25:091419browse

如何使用 FabricJS 将对象添加到画布?

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.

Syntax

canvas.add(object: fabric.Object);

Parameters

  • Object - The type of this parameter is fabric.Object and Saving the object

Example 1: Create an instance of the object in canvas.add()

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>

Output

How to add objects to canvas using FabricJS?

Example 2: Create an object and then add it to the canvas

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>

Output

How to add objects to canvas using FabricJS?

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete