如何使用 FabricJS 停用橢圓的居中縮放?


在本教程中,我們將學習如何使用 FabricJS 停用居中縮放橢圓。橢圓是 FabricJS 提供的各種形狀之一。為了建立橢圓,我們將不得不建立一個fabric.Ellipse類的例項並將其新增到畫布上。當透過控制元件進行縮放時,將“true”值賦予centeredScaling屬性,會使用中心作為物件的變換原點。

語法

new fabric.Ellipse({ centeredScaling: Boolean }: Object)

引數

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

選項鍵

  • centeredScaling - 此屬性接受一個布林值。當此屬性為True時,物件使用中心作為其變換原點。

示例 1

centeredScaling作為鍵併為其分配“true”值

以下示例演示了當啟用centeredScaling屬性時橢圓物件的行為。當我們將物件放大時,變換原點是橢圓的中心。

<!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 disable the centered scaling of Ellipse using FabricJS?</h2>
      <p>Select the object and stretch it from its corners. The ellipse will scale up from its center. This is the default behavior.</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: 215,
            top: 100,
            fill: "white",
            rx: 90,
            ry: 50,
            stroke: "#c154c1",
            strokeWidth: 5,
            borderColor: "#daa520",
            centeredScaling: true,
         });

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

示例 2

停用 centeredScaling 屬性

我們可以透過為其分配“false”值來停用centeredScaling屬性。這將不再使用橢圓的中心作為變換中心。以下是一段程式碼,用於演示這一點 -

<!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 disable the centered scaling of Ellipse using FabricJS?</h2>
      <p>Select the object and stretch it from its corners. You will notice the object scales up but not from its center because we have set <b>centeredScaling</b> as False. </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: 215,
            top: 100,
            fill: "",
            rx: 90,
            ry: 50,
            stroke: "#c154c1",
            strokeWidth: 5,
            borderColor: "#daa520",
            centeredScaling: false,
         });

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

更新於: 2022年5月24日

107 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.