如何使用 FabricJS 為橢圓新增描邊?


在本教程中,我們將學習如何使用 FabricJS 為橢圓新增描邊。橢圓是 FabricJS 提供的各種形狀之一。為了建立橢圓,我們必須建立一個fabric.Ellipse類的例項並將其新增到畫布中。我們的橢圓物件可以透過多種方式進行自定義,例如更改其尺寸、新增背景顏色或更改圍繞物件繪製的線條的顏色。我們可以透過使用stroke屬性來實現這一點。

語法

new fabric.Ellipse({ stroke : String }: Object)

引數

  • options (可選) − 此引數是一個物件,它為我們的橢圓提供了額外的自定義選項。使用此引數可以更改物件的許多屬性,其中stroke屬性是用於更改顏色、游標、描邊寬度等的屬性。

選項鍵

  • stroke − 此屬性接受一個字串,並確定該物件邊框的顏色。

示例 1

使用十六進位制值作為鍵傳遞stroke

讓我們來看一個例子,瞭解當使用stroke屬性時我們的橢圓物件是如何顯示的。十六進位制顏色程式碼以“#”開頭,後面跟著一個六位數字,代表一種顏色。在本例中,我們使用了“#ff4500”,這是一種橙紅色。

<!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>How to add stroke to an Ellipse using FabricJS?</h2>
      <p>Notice the orange-red outline which appears because we have used the "stroke" property and supplied it with a hexadecimal value "#ff4500"</p>
      <canvas id="canvas"></canvas>
     
      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         
         // Initiate an ellipse instance
         var ellipse = new fabric.Ellipse({
            left: 115,
            top: 50,
            rx: 80,
            ry: 50,
            fill: "#4169e1",
            stroke: "#ff4500",
            strokeWidth: 5,
         });
         
         // Adding it to the canvas
         canvas.add(ellipse);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

示例 2

將 rgba 值傳遞給stroke屬性

在這個例子中,我們將看到如何為stroke屬性賦值“rgba”值。我們可以使用 RGBA 值代替十六進位制顏色程式碼,它代表:紅色、綠色、藍色和 alpha。alpha 引數指定顏色的不透明度。在這個例子中,我們使用了 rgba 值 (255,69,0,0.5),這是一種不透明度為 0.5 的橙紅色。

<!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>How to add stroke to an Ellipse using FabricJS?</h2>
      <p> Notice the outline of the ellipse. Here we have used the "stroke" property and supplied it with an "rgba" value.</p>
      <canvas id="canvas"></canvas>
     
      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         
         // Initiate an ellipse instance
         var ellipse = new fabric.Ellipse({
            left: 115,
            top: 50,
            rx: 80,
            ry: 50,
            fill: "#4169e1",
            stroke: "rgba(255,69,0,0.5)",
            strokeWidth: 5,
         });
         
         // Adding it to the canvas
         canvas.add(ellipse);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

更新於:2022年5月24日

174 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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