如何使用 FabricJS 锁定矩形的水平倾斜?


在本教程中,我们将学习如何使用 FabricJS 锁定矩形的水平倾斜。就像我们可以在画布上指定矩形对象的位​​置、颜色、不透明度和尺寸一样,我们还可以指定是否要停止对象的水平倾斜。这可以通过使用lockSkewingX属性来完成。

语法

new fabric.Rect({ 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 Rectangle object in the canvas</h2>
   <p>Press the shift-key and drag the object along the X or Y-axis to see 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 rectangle object
      var rect = new fabric.Rect({
         left: 155,
         top: 90,
         width: 170,
         height: 70,
         fill: "#6f2da8",
         padding: 9,
         stroke: "#b666d2",
         strokeWidth: 5,
      });

      // Add it to the canvas
      canvas.add(rect);
   </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>Press the shift-key and try to drag the object in the horizontal direction. You will notice 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 rectangle object
      var rect = new fabric.Rect({
         left: 155,
         top: 90,
         width: 170,
         height: 70,
         fill: "#6f2da8",
         padding: 9,
         stroke: "#b666d2",
         strokeWidth: 5,
         lockSkewingX: true,
      });

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

更新于: 2022年6月29日

380 次浏览

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.