如何使用 FabricJS 鎖定三角形的水平傾斜?


在本教程中,我們將學習如何使用 FabricJS 鎖定三角形的水平傾斜。就像我們可以指定畫布中三角形物件的位 置、顏色、不透明度和尺寸一樣,我們也可以指定是否要停止物件的水平傾斜。這可以透過使用`lockSkewingX`屬性來完成。

語法

new fabric.Triangle({ lockSkewingX : Boolean }: Object)

引數

  • 選項(可選) - 此引數是一個物件,它為我們的三角形提供了額外的自定義功能。使用此引數,可以更改與`lockSkewingX`屬性相關的物件的許多屬性,例如顏色、游標、筆劃寬度等。

選項鍵

  • lockSkewingX - 此屬性接受布林值。如果我們將其賦值為“true”,則物件的水平傾斜將被鎖定。

示例 1

畫布中三角形物件的預設行為

讓我們來看一個程式碼示例,瞭解在不使用`lockSkewingX`屬性時三角形物件的預設行為。透過按住**Shift 鍵**,然後沿水平或垂直方向拖動,可以在水平和垂直方向上傾斜物件。

<!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>Press the shift-key and drag the edge along the X-axis or Y-axis and observe that skewing is possible in both directions.</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

將`lockSkewingX`作為鍵並賦值為'true'

在這個例子中,我們將看到如何使用`lockSkewingX`屬性來阻止三角形物件水平傾斜。正如我們所看到的,雖然我們可以垂直傾斜三角形物件,但我們不允許水平執行相同的操作。

<!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 lockSkewingX as key with 'true' value</h2>
   <p>You can try and see that skewing along the X-axis is no longer feasible.</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,
         lockSkewingX: true,
      });

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

更新於:2022年6月24日

83 次檢視

啟動您的職業生涯

完成課程獲得認證

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