如何使用 FabricJS 設定畫布上選擇區域邊框的寬度?


在本文中,我們將學習如何使用 FabricJS 設定畫布上選擇區域邊框的寬度。選擇區域指示使用滑鼠選擇的區域,該區域下的所有物件都將被選中。FabricJS 允許我們使用 selectionLineWidth 屬性調整選擇區域邊框的寬度。

語法

new fabric.Canvas(element: HTMLElement|String, { selectionLineWidth: Number }: Object)

引數

  • 元素 − 此引數是 <canvas> 元素本身,可以使用 document.getElementById() 或 <canvas> 元素本身的 id 獲取。FabricJS 畫布將在此元素上初始化。

  • 選項(可選) − 此引數是一個物件,它為我們的畫布提供了額外的自定義功能。使用此引數可以更改與畫布相關的顏色、游標、邊框寬度以及許多其他屬性,其中 selectionLineWidth 是一個屬性。它接受一個數字,該數字確定選擇邊框中使用的線條的寬度。其預設值為 1。

示例 1

將 selectionLineWidth 鍵傳遞給類

讓我們看一個程式碼示例,說明我們如何使用 FabricJS 設定畫布中選擇區域邊框的寬度。selectionLineWidth 引數接受數字作為值。我們設定的數字越大,畫布區域的邊框就越寬。

<!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>Setting the width of the selection area border in canvas using FabricJs</h2>
   <p>Select an area around the object to see the width of the selection area border.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         selectionLineWidth: 23,
      });
      // Creating an instance of the fabric.Rect class
      var rect = new fabric.Rect({
         left: 170,
         top: 90,
         width: 60,
         height: 80,
         fill: "#006400",
         angle: 90,
      });
      // Adding it to the canvas
      canvas.add(rect);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

示例 2

將 selectionLineWidth 與 selectionColor 和 selectionBorderColor 結合使用

我們可以將 selectionLineWidth 引數與其他引數(如 selectionColorselectionBorderColor 屬性)結合使用,這些屬性分別允許我們設定選定區域的顏色並調整該選定區域的邊框顏色。讓我們看看程式碼是什麼樣的

<!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>Setting the width of selection area border in canvas using Fabric</h2>
   <p>Select an area around the object to see the selection color and selection border color.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         selectionLineWidth: 3,
         selectionColor: "rgba(42,82,190,0.3)",
         selectionBorderColor: "black",
      });
      // Creating an instance of the fabric.Rect class
      var rect = new fabric.Rect({
         left: 170,
         top: 90,
         width: 60,
         height: 80,
         fill: "#006400",
         angle: 90,
      });
      // Adding it to the canvas
      canvas.add(rect);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

更新於: 2022年5月19日

659 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.