如何使用 FabricJS 設定畫布上選擇區域的顏色?


在本文中,我們將學習如何使用 FabricJS 設定畫布上選擇區域的顏色。我們可以使用 selectionColor 屬性調整顏色。

語法

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

引數

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

  • options (可選) − 此引數是一個物件,它為我們的畫布提供了額外的自定義選項。使用此引數,可以更改與畫布相關的顏色、游標、邊框寬度等許多其他屬性,其中 selectionColor 是一個屬性,我們可以用它來指示選擇的顏色。selectionColor 的預設值為 rgba(100,100,255,0.3)。

示例 1

將 selectionColor 鍵傳遞給類

selectionColor 屬性接受一個字串,該字串確定選擇的顏色。我們可以使用 RGBA 值,它代表:紅色、藍色、綠色和 alpha。alpha 引數指定顏色的不透明度。讓我們看一個程式碼示例,說明如何使用 FabricJS 設定畫布中選擇區域的顏色。

<!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 color of a selection area using FabricJs</h2>
   <p>Select an area around the object to see the color of the selection area.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         selectionColor: "rgba(0,0,0,0.4)",
      });
      // 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

使用顏色名稱而不是 RGBA 值

我們也可以使用特定的顏色而不是使用 RGBA 值。在此示例中,selectionColor 屬性已設定為顏色“紅色”。

<!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 color of a selection area using FabricJs</h2>
   <p>Select an area around the object to see the color of the selection area.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         selectionColor: "red",
      });
      // 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日

719 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.