FabricJS – 如何確定多邊形物件的填充或描邊先繪製?


我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表徵。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。為了確定填充或描邊應該先繪製,我們使用paintFirst屬性。

語法

new fabric.Polygon( points: Array, { paintFirst: String }: Object )

引數

  • points − 此引數接受一個陣列,表示構成多邊形物件的點的陣列,其中每個點都是一個具有 x 和 y 屬性的物件。

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

選項鍵

paintFirst − 此屬性接受一個字串值,該值定義是先繪製填充還是描邊。預設值為“fill”。

示例 1:多邊形物件的預設外觀

讓我們來看一個程式碼示例,說明當沒有應用paintFirst屬性時多邊形物件的外觀。在這種情況下,使用預設值“fill”。這意味著在繪製物件時,將先繪製填充顏色,然後繪製描邊顏色。

<!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 the default appearance of polygon object</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: 200, y: 10 },
            { x: 250, y: 50 },
            { x: 250, y: 180 },
            { x: 150, y: 180 },
            { x: 150, y: 50 },
            { x: 200, y: 10 },
         ],
         {
            fill: "green",
            stroke: "blue",
            strokeWidth: 20,
         }
      );
      
      // Adding it to the canvas
      canvas.add(polygon);
   </script>
</body> 
</html> 

示例 2:使用 paintFirst 屬性

讓我們來看一個程式碼示例,說明如何透過使用paintFirst屬性來更改多邊形物件的預設行為。在這裡,我們將paintFirst屬性的值設定為“stroke”。這確保了先繪製描邊而不是填充。

<!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 the paintFirst property</h2>
   <p>You can see that the stroke is painted first 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);
      
      // Initiating a polygon object
      var polygon = new fabric.Polygon(
         [
            { x: 200, y: 10 },
            { x: 250, y: 50 },
            { x: 250, y: 180 },
            { x: 150, y: 180 },
            { x: 150, y: 50 },
            { x: 200, y: 10 },
         ],
         {
            fill: "green",
            stroke: "blue",
            strokeWidth: 20,
            paintFirst: "stroke",
         }
      );
      
      // Adding it to the canvas
      canvas.add(polygon);
   </script>
</body> 
</html>

結論

在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 確定多邊形的填充或描邊應該先繪製。

更新於:2022年12月29日

瀏覽量:153

啟動您的職業生涯

完成課程獲得認證

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