如何使用FabricJS鎖定圓形的水平縮放?


在本教程中,我們將學習如何使用FabricJS鎖定圓形的水平縮放。就像我們可以在畫布上指定圓形物件的位移、顏色、不透明度和尺寸一樣,我們也可以指定是否要停止物件的水平縮放。這可以透過使用`lockScalingX`屬性來實現。

語法

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

引數

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

選項鍵

  • lockScalingX − 此屬性接受一個布林值。如果我們將其賦值為“true”,則物件的水平縮放將被鎖定。

示例1

畫布中圓形物件的預設行為

讓我們來看一個例子,瞭解當不使用`lockScalingX`屬性時圓形物件的預設行為。可以水平和垂直方向縮放物件。

<!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>Locking the horizontal scaling of a circle using FabricJS</h2>
      <p>You can select the circle and scale it freely in any direction. This is the default behavior. Here we have not applied the <b>lockScalingX</b> property, but by default, it is set to False. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle({
            left: 115,
            top: 50,
            fill: "white",
            radius: 50,
            stroke: "black",
            strokeWidth: 5
         });

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

示例2

將lockScalingX作為鍵並賦值為'true'

在這個例子中,我們將看到如何使用`lockScalingX`屬性來阻止圓形物件進行水平縮放。我們可以看到,雖然可以垂直縮放圓形物件,但我們不允許進行水平縮放。

<!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>Locking the horizontal scaling of circle using FabricJS</h2>
      <p>Here, you will no longer be able to scale the circle horizontally, as we have set <b>lockScalingX</b> to True. You can however scale the circle in vertical direction. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle({
            left: 115,
            top: 50,
            fill: "white",
            radius: 50,
            stroke: "black",
            strokeWidth: 5,
            lockScalingX: true
         });

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

更新於:2022年5月25日

136 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告