如何使用 FabricJS 鎖定矩形的水平移動?


在本教程中,我們將學習如何使用 FabricJS 鎖定矩形的水平移動。就像我們可以在畫布上指定矩形物件的的位置、顏色、不透明度和尺寸一樣,我們也可以指定是否希望它只在 Y 軸上移動。這可以透過使用 lockMovementX 屬性來實現。

語法

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

引數

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

選項鍵

  • lockMovementX - 此屬性接受一個布林值。如果我們為其分配一個“true”值,則物件將不再能夠在水平方向上移動。

示例 1

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

讓我們看一個程式碼示例,以瞭解當lockMovementX屬性未分配為 True 值時,我們如何自由地在 X 軸或 Y 軸上移動我們的矩形物件。

<!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>Drag the rectangle across the X-axis and Y-axis to see that movement is
allowed 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 rectangle object
      var rect = new fabric.Rect({
         left: 55,
         top: 90,
         width: 170,
         height: 70,
         fill: "black",
         padding: 9,
         stroke: "#483d8b",
         strokeWidth: 5,
      });

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

示例 2

將 lockMovementX 作為鍵傳遞,並賦予 True 值

在本例中,我們將看到如何鎖定矩形物件的水平移動。透過為 lockMovementX 屬性分配 True 值,我們實際上停止了水平方向的移動。

<!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 lockMovementX as key with a True value</h2>
   <p>Drag the rectangle across the X-axis and Y-axis, and observe that its movement is restricted 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: 55,
         top: 90,
         width: 170,
         height: 70,
         fill: "black",
         padding: 9,
         stroke: "#483d8b",
         strokeWidth: 5,
         lockMovementX: true,
      });

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

更新於: 2022-06-29

364 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.