如何使用 FabricJS 建立帶有圓形的畫布?


在本教程中,我們將學習如何使用 FabricJS 建立帶有圓形物件的畫布。圓形是 FabricJS 提供的各種形狀之一。為了建立圓形,我們需要建立一個 fabric.Circle 類的例項並將其新增到畫布中。

語法

new fabric.Circle({ radius: Number }: Object)

引數

  • options (可選) − 此引數是一個 物件,它為我們的物件提供額外的自定義。使用此引數,可以更改與圓形相關的屬性,例如顏色、游標、筆觸寬度以及許多其他屬性,其中 **半徑** 是一個屬性。

選項鍵

  • radius − 此屬性接受一個 數字,用於確定圓形的半徑。如果我們沒有指定半徑,我們的圓形將不會顯示在畫布上。

示例 1

建立 fabric.Circle() 的例項並將其新增到我們的畫布中

讓我們看一個如何將圓形新增到畫布的示例。在這裡,我們建立了一個半徑為 50px 的圓形。stroke 屬性表示邊框顏色,strokeWidth 指定邊框寬度。我們使用天藍色填充物件,其十六進位制值為 #80daeb

<!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>Creating a canvas with circle using FabricJS</h2>
         <p>Here we have created a circle of radius 50px over a canvas. In addition, we have used the <b>fill</b> and <b>stroke</b> properties to color its body and outline. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         
         // Creating an instance of the fabric.Circle class
         var circle = new fabric.Circle({
            left: 215,
            top: 100,
            radius: 50,
            fill: "#80daeb",
            stroke: "#00b7eb",
            strokeWidth: 2,
         });
         
         // Adding it to the canvas
         canvas.add(circle);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

示例 2

使用 set 方法操作圓形物件

在此示例中,我們使用 set 方法為圓形分配了屬性,該方法是值的 setter。可以使用此方法更改與筆觸、筆觸寬度、半徑、縮放、旋轉等相關的任何屬性。

<!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>Creating a canvas with circle using FabricJS</h2>
      <p>Here we have used the <b>set</b> method to create a circle of radius 40px and then filled the object with a color. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle();
         canvas.add(circle);
         
         // Use set to set the properties
         circle.set("radius", 40);
         circle.set("fill", "green");
         circle.set({
            stroke: "rgba(133, 187, 101, 0.7)",
            strokeWidth: 4
         });
         circle.set("left", 50);
         circle.set("top", 50);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

更新於: 2022-05-25

622 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.