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


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

語法

new fabric.Triangle({ 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 Triangle object in the canvas</h2>
   <p>You can scale the triangle 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 triangle object
      var triangle = new fabric.Triangle({
         left: 105,
         top: 70,
         width: 90,
         height: 80,
         fill: "#746cc0",
         stroke: "#967bb6",
         strokeWidth: 5,
      });

      // Add it to the canvas
      canvas.add(triangle);
   </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 'true' value</h2>
   <p>You can see a not-allowed cursor if you try to scale the triangle 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 triangle object
      var triangle = new fabric.Triangle({
         left: 105,
         top: 70,
         width: 90,
         height: 80,
         fill: "#746cc0",
         stroke: "#967bb6",
         strokeWidth: 5,
         lockScalingX: true,
      });

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

更新於: 2022-06-24

84 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.