如何使用 FabricJS 锁定圆形的垂直移动?


在本教程中,我们将学习如何使用 FabricJS 锁定圆形的垂直移动。就像我们可以在画布上指定圆形对象的位移、颜色、不透明度和尺寸一样,我们也可以指定是否只想让它在 X 轴上移动。这可以通过使用 `lockMovementY` 属性来实现。

语法

new fabric.Circle({ lockMovementY: Boolean }: Object)

参数

  • `options` (可选) − 此参数是一个 `Object`,它为我们的圆形提供了额外的自定义选项。使用此参数,可以更改与 `lockMovementY` 属性相关的对象的许多属性,例如颜色、光标、笔触宽度等等。

选项键

  • `lockMovementY` − 此属性接受一个 `布尔值`。如果我们为其赋值 `true`,则该对象将无法再在垂直方向上移动。

示例 1

画布中圆形对象的默认行为

让我们来看一个代码示例,了解当 `lockMovementY` 属性未赋值为 `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>Locking the vertical movement of circle using FabricJS</h2>
      <p>You can select the circle and move it freely. Here we have not applied the <b>lockMovementY</b> property, but by default, it is set to False.</p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle({
            left: 115,
            top: 50,
            fill: "white",
            radius: 50,
            stroke: "black",
            strokeWidth: 5
         });

         // Adding it to the canvas
         canvas.add(circle);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

示例 2

将 `lockMovementY` 作为键并赋值 `true`

在这个例子中,我们将看到如何锁定圆形对象的垂直移动。通过将 `lockMovementY` 属性赋值为 `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>Locking the vertical movement of circle using FabricJS</h2>
      <p>Select the object and try to move it around. You will observe that the object can be moved horizontally, but its vertical movement is locked. Here we have set <b>lockMovementY</b> to True.</p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle({
            left: 115,
            top: 50,
            fill: "white",
            radius: 50,
            stroke: "black",
            strokeWidth: 5,
            lockMovementY: true
         });

         // Adding it to the canvas
         canvas.add(circle);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

更新于:2022年5月25日

浏览量:113

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.