如何使用 FabricJS 中的 Polygon 物件繪製八邊形?


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

語法

new fabric.Polygon( points: Array, options: Object )

引數

  • points − 此引數接受一個數組,該陣列表示構成多邊形物件的點的陣列。

  • options (可選) − 此引數是一個物件,它為我們的物件提供額外的自定義選項。使用此引數,可以更改與 Polygon 物件相關的原點、筆觸寬度和許多其他屬性。

示例 1:Polygon 物件的預設外觀

讓我們看一個程式碼示例,說明我們如何繪製任何一般多邊形物件。我們需要指定一個點陣列,其中每個點都是一個具有 x 和 y 的物件。指定點陣列至關重要,否則我們的多邊形物件將不會渲染到畫布上。我們還可以使用各種屬性來自定義多邊形物件。這裡,我們透過分配填充顏色、筆觸顏色並將strokeWidth設定為 2 來自定義多邊形物件。

<!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>Default appearance of polygon object</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);
      
      // Initiate a polygon instance
      var polygon = new fabric.Polygon(
         [
            { x: 500, y: 20 },
            { x: 550, y: 60 },
            { x: 550, y: 200 },
            { x: 350, y: 200 },
            { x: 350, y: 60 },
            { x: 500, y: 20 },
         ],
         {
            fill: "black",
            stroke: "blue",
            strokeWidth: 2,
         }
      );
      
      // Adding it to the canvas
      canvas.add(polygon);
   </script>
</body>
</html> 

示例 2:使用 Polygon 繪製八邊形

讓我們看一個程式碼示例,瞭解如何使用多邊形繪製八邊形。八邊形是一個有 8 條邊和 8 個角的多邊形。雖然可以繪製許多型別的八邊形,但在此示例中,我們將演示如何繪製一個正八邊形,其中所有邊的長度都相等。

<!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>Drawing an octagon using Polygon</h2>
   <p>You can see an octagon 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);

      // Initiate a polygon object
      var octagon = new fabric.Polygon(
         [
            { x: -37.282, y: 90 },
            { x: 37.282, y: 90 },
            { x: 90, y: 37.282 },
            { x: 90, y: -37.282 },
            { x: 37.282, y: -90 },
            { x: -37.282, y: -90 },
            { x: -90, y: -37.282 },
            { x: -90, y: 37.282 },
         ],
         {
            stroke: "red",
            left: 110,
            top: 10,
            strokeWidth: 2,
            strokeLineJoin: "bevil",
         } 
      );
   
      // Adding it to the canvas
      canvas.add(octagon);
   </script>
</body>
</html> 

結論

在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 中的 Polygon 繪製八邊形。

更新於: 2023年1月2日

266 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.