如何使用 FabricJS 的 Polyline 類繪製六邊形?


我們可以透過建立 fabric.Polyline 的例項來建立一個 Polyline 物件。Polyline 物件可以用一組連線的直線段來表示。因為它屬於 FabricJS 的基本元素之一,所以我們也可以透過應用角度、不透明度等屬性來輕鬆定製它。六邊形是一個具有六條邊的封閉二維多邊形。

語法

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

引數

  • points − 此引數接受一個陣列,表示構成 polyline 物件的點陣列。

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

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

在開始建立之前,讓我們看看如何將 polyline 物件新增到畫布的程式碼示例。唯一必需的引數是points 陣列,而第二個引數是可選的options 物件。

<!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.Polyline() and adding it to our canvas</h2>
   <p>You can see that the polyline object has 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 points array
      var points = [
         { x: 30, y: 50 },
         { x: 0, y: 0 },
         { x: 60, y: 0 },
      ];
      
      // Initiating a polyline object
      var polyline = new fabric.Polyline(points, {
         left: 100,
         top: 40,
         fill: "white",
         strokeWidth: 4,
         stroke: "teal",
      });
      
      // Adding it to the canvas
      canvas.add(polyline);
   </script>
</body>
</html>

示例 2:使用 Polyline 建立六邊形

在這個例子中,我們將使用 Polyline 例項建立一個六邊形。我們可以選擇座標,以便形狀形成如下所示的六邊形。

<!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 a hexagon with Polyline</h2>
   <p>You can see the hexagon in the canvas now</p>
   <canvas id="canvas"></canvas>
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Create a points Array
      var points = [
         { x: 50, y: 0 },
         { x: 25, y: 43.30},
         { x: -25, y: 43.301 },
         { x: -50, y: 0},
         { x: -25, y: -43.301},
         { x: 25, y: -43.301 },
         { x: 50, y: 0 },
      ];
      
      // Initiating a polyline object
      var polyline = new fabric.Polyline(points);
      
      // Set the properties
      polyline.set("stroke", "teal");
      polyline.set("strokeWidth", 3);
      polyline.set("fill", "white");
      polyline.set("top", 50);
      polyline.set("left", 100);
      polyline.set("scaleX", 0.75);
      polyline.set("scaleY", 0.75);
      
      // Adding it to the canvas
      canvas.add(polyline);
   </script>
</body>
</html>

更新於:2023年2月16日

128 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.