如何使用 FabricJS 停用圓形的居中旋轉?


在本教程中,我們將學習如何使用 FabricJS 停用圓形的居中旋轉。圓形是 FabricJS 提供的各種形狀之一。為了建立一個圓形,我們將建立一個 fabric.Circle 類的例項並將其新增到畫布上。預設情況下,FabricJS 中的所有物件都使用其中心作為旋轉點。但是,我們可以使用 centeredRotation 屬性更改此行為。

語法

new fabric.Circle({ centeredRotation: Boolean }: Object)

引數

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

選項鍵

  • centeredRotation - 此屬性接受一個 Boolean 值,允許我們控制物件在透過控制元件旋轉時是否使用其變換原點作為中心點。其預設值為 True

示例 1

FabricJS 中圓形旋轉的預設行為

讓我們看一個描述圓形物件的預設行為的示例。由於 centeredRotation 屬性預設設定為 True,因此圓形物件使用其中心作為旋轉點。

<!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>Disabling the centered rotation of circle using FabricJs</h2>
      <p>Select the object and rotate it by holding its controlling corner at the top. The circle will rotate around its center. It is the default behavior. Here we have not used the <b>centeredRotation</b> property but it is by default set to True. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var cir = new fabric.Circle({
            left: 215,
            top: 100,
            fill: "white",
            radius: 50,
            stroke: "#c154c1",
            strokeWidth: 5,
            borderColor: "#daa520",
         });

         // Adding it to the canvas
         canvas.add(cir);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

示例 2

使用值為“false”的centeredRotation

既然我們已經看到了預設行為,讓我們看一段程式碼來了解當 centeredRotation 屬性被賦值為 False 時會發生什麼。

<!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>Disabling the centered rotation of circle using FabricJs</h2>
      <p>Select the object and rotate it by holding its controlling corner at the top. Now the circle will not rotate around its cente because we have used the <b>centeredRotation</b> property and set it False. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var cir = new fabric.Circle({
            left: 215,
            top: 100,
            fill: "white",
            radius: 50,
            stroke: "#c154c1",
            strokeWidth: 5,
            borderColor: "#daa520",
            centeredRotation: false
         });

         // Adding it to the canvas
         canvas.add(cir);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

更新於: 2022年5月25日

200 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.