FabricJS – 如何使用函式而不是建構函式設定多邊形物件的屬性?


我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表徵。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性來輕鬆自定義它。

語法

set(key: String, value: String | Boolean | Number | Object | Function)

引數

  • key − 此引數接受一個字串,指定我們要設定的屬性。

  • value − 此引數接受要為屬性設定的值。

示例 1:建立 fabric.Polygon() 的例項並將其新增到我們的畫布

讓我們看一個程式碼示例,說明我們如何透過建立fabric.Polygon的例項來建立一個多邊形。可以看出,我們使用建構函式添加了“top”和“left”的屬性。

<!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>
      Creating an instance of fabric.Polygon() and adding it to our canvas
   </h2>
   <p>You can see that a Polygon object has been added to the canvas</p>
   <canvas id="canvas"></canvas> 
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Initiating a polygon object
      var polygon = new fabric.Polygon(
         [
            { x: -20, y: -35 },
            { x: 20, y: -35 },
            { x: 40, y: 0 },
            { x: 20, y: 35 },
            { x: -20, y: 35 },
            { x: -40, y: 0 },
         ],
         {
            top: 50,
            left: 50,
         }
      );
      
      // Adding it to the canvas
      canvas.add(polygon);
   </script>
</body>
</html> 

示例 2:使用函式設定多邊形物件的屬性

讓我們看一個程式碼示例,瞭解使用函式設定屬性時多邊形物件是什麼樣的。這裡我們初始化了一個名為addProperties的函式,該函式使用set方法新增“stroke”、“left”、“fill”、“top”和“selectable”的屬性。當我們呼叫該函式時,這些屬性將被新增到物件中。

<!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>Using a function to set the properties of Polygon object</h2>
   <p>You can see that the properties have been added</p>
   <canvas id="canvas"></canvas>
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Initiating a polygon object
      var polygon = new fabric.Polygon([
         { x: -20, y: -35 },
         { x: 20, y: -35 },
         { x: 40, y: 0 },
         { x: 20, y: 35 },
         { x: -20, y: 35 },
         { x: -40, y: 0 },
      ]);
      
      // Initializing addProperties function
      function addProperties(obj) {
         obj.set("stroke", "red");
         obj.set("left", 100);
         obj.set("fill", "black");
         obj.set("top", 70);
         obj.set("selectable", true);
      }
      
      // Calling addProperties function 
      addProperties(polygon);
      
      // Adding it to the canvas
      canvas.add(polygon);
   </script>
</body>
</html>

結論

在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 使用函式而不是建構函式來設定多邊形物件的屬性。

更新於: 2023年1月2日

101 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.