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


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

語法

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

引數

  • 選項(可選) - 此引數是一個物件,它為我們的矩形提供了額外的自定義功能。使用此引數,可以更改與 `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>Default behaviour of a Rectangle object in the canvas</h2>
   <p>You can scale the rectangle in horizontal and vertical directions to verify that scaling in both directions is possible.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // Initiate a rectangle object
      var rect = new fabric.Rect({
         left: 155,
         top: 90,
         width: 170,
         height: 70,
         fill: "white",
         padding: 9,
         stroke: "#483d8b",
         strokeWidth: 5,
      });

      // Add it to the canvas
      canvas.add(rect);
   </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>Passing lockScalingX as key with a True value</h2>
   <p>You can see a not-allowed cursor if you try to scale the rectangle in the
horizontal direction.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // Initiate a rectangle object
      var rect = new fabric.Rect({
         left: 155,
         top: 90,
         width: 170,
         height: 70,
         fill: "white",
         padding: 9,
         stroke: "#483d8b",
         strokeWidth: 5,
         lockScalingX: true,
      });

      // Add it to the canvas
      canvas.add(rect);
   </script>
</body>
</html>

更新於:2022年6月29日

370 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.