如何使用 Fabric.js 更改畫布圓形的背景顏色?


Fabric.js 的 Circle 類用於透過 fabric.Circle 物件提供圓形形狀。Circle 物件用於提供圓形形狀,該圓形可移動,並且可以根據需要進行拉伸。對於筆觸、顏色、寬度、高度和填充顏色,Circle 是可自定義的。與 canvas 類相比,Circle 類提供了更豐富的功能。

在這裡,我們使用 Circle 物件的 backgroundColor 屬性來更改畫布圓形的背景顏色。我們可以透過為該屬性定義值來更改背景顏色。

語法

以下是 Circle 的語法:

fabric.Circle({
   radius: number,
   backgroundColor: string,
   fill: string,
   stroke: string,
   strokewidth: int
});

引數

  • radius - 用於指定圓形的半徑

  • fill - 用於指定填充顏色

  • stroke - 用於指定筆觸顏色

  • strokeWidth - 用於指定筆觸的寬度

  • radius - 用於指定半徑

  • backgroundColor - 指定背景的顏色

示例

在本示例中,我們將初始化圓形和畫布的例項,它有助於使用 backgroundColor 屬性更改圓形的背景顏色並在畫布上渲染圓形。

<html>
   <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
   </head>
   <body>
      <h2>Changing the background color of a canvas circle</h2>
      <p>Select the textbox to see that the controlling corners.</p>
      <p>Background color of Canvas Circle is changed to "yellow".</p>
      <canvas id="canvas" width="550" height="450" ></canvas>
      <script>
         var canvas = new fabric.Canvas("canvas");
         var round = new fabric.Circle({
            top: 50,
            left: 50,
            radius: 80,
            backgroundColor: 'yellow'
         });
         canvas.add(round);
      </script>
   </body>
</html>

正如我們在示例中看到的,這裡我們使用了 Fabric.js 的 Circle 類,該類用於透過 fabric.Circle 物件提供圓形形狀。在這裡,我們將畫布圓形的背景顏色更改為黃色。

讓我們再舉一個例子,我們將學習如何更改具有主體和輪廓顏色的畫布圓形的背景顏色。

示例

我們將初始化 Canvas 和 Circle 的例項,它有助於使用 backgroundColor 屬性更改圓形的背景顏色並在畫布上渲染圓形。在 Circle 類物件下,我們定義了諸如 fill、stroke、strokeWidth、left、top、radius 和 backgroundColor 之類的屬性,這些屬性為圓形主體和輪廓提供顏色。

<html>
   <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
   </head>
   <body>
      <h2>Changing the background color of a canvas circle</h2>
      <p>Select the textbox to see that the controlling corners.</p>
      <p>Background color of Canvas Circle is changed to "green".</p>
      <canvas id="canvas" width="600" height="300" style="border:1px solid #00008B"></canvas>
      <script>
         var canvas = new fabric.Canvas("canvas");
         var round1 = new fabric.Circle({
            radius: 80,
            left: 180,
            top: 80,
            fill: "#70daeb",
            stroke: "#00b7eb",
            strokeWidth: 2,
            backgroundColor: 'green'
         });
         canvas.add(round1);
      </script>
   </body>
</html>

結論

在本文中,我們看到了兩個不同的示例,在第一個示例中,我們使用了 Circle 類的 backgroundColor 屬性將圓形的背景顏色更改為黃色。

在第二個示例中,我們使用了 Circle 類及其屬性(如 radius、backgroundColor、fill、top、left、stroke 和 strokeWidth)來更改圓形的背景顏色以及圓形主體和輪廓的顏色。

更新於:2023年2月21日

572 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.