如何使用 FabricJS 在移动物体上创建带有进度光标的文本框?


在本教程中,我们将学习如何使用 FabricJS 创建一个在移动对象上显示进度光标的文本框。进度是可用的原生 光标 样式之一,也可以在 FabricJS 画布中使用。FabricJS 提供各种类型的光标,例如默认光标、全滚动光标、十字光标、列调整大小光标、行调整大小光标等,这些光标在底层重用了原生光标。`moveCursor` 属性设置在画布中移动对象时光标的样式。

语法

new fabric.Textbox(text: String, { moveCursor: String }: Object)

参数

  • text − 此参数接受一个字符串,即我们想要在文本框内显示的文本字符串。

  • options (可选) − 此参数是一个对象,它为我们的文本框提供额外的自定义选项。使用此参数可以更改与对象相关的许多属性,包括颜色、光标、描边宽度等等,其中`moveCursor`也是一个属性。

选项键

  • moveCursor − 此属性接受一个字符串,允许我们在画布上移动此文本框对象时设置默认光标值。该值决定了移动画布对象时使用的光标类型。

示例 1

移动对象时默认光标值

默认情况下,当我们在画布中移动文本框对象时,光标类型为`move`。让我们来看一个代码示例来理解这一点。

<!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 cursor value when object is moved around the canvas</h2>
   <p>Move the cursor around the textbox and observe that the default cursor type is "move".</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 textbox object
      var textbox = new fabric.Textbox("Do it with passion or not at all.", {
         backgroundColor: "#fffff0",
         width: 400,
         left: 110,
         top: 70,
         fill: "#e1a95f",
         strokeWidth: 2,
         stroke: "#a40000",
         textAlign: "center",
      });

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

示例 2

将 `moveCursor` 属性作为键值对传递

在这个例子中,我们将`moveCursor`键作为值为“progress”传递给文本框类。这将确保当我们在画布中移动对象时,光标值为“progress”。下面的代码示例对此进行了说明:

<!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 the moveCursor property as key with a value</h2>
   <p> Move the cursor around the textbox and observe that the cursor type has now changed to "progress"</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 textbox object
      var textbox = new fabric.Textbox("Do it with passion or not at all.", {
         backgroundColor: "#fffff0",
         width: 400,
         left: 110,
         top: 70,
         fill: "#e1a95f",
         strokeWidth: 2,
         stroke: "#a40000",
         textAlign: "center",
         moveCursor: "progress",
      });

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

更新于:2022年7月29日

浏览量:119

开启你的职业生涯

完成课程并获得认证

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