如何使用 FabricJS 设置矩形描边的宽度?


在本教程中,我们将学习如何使用 FabricJS 设置矩形的描边宽度。矩形是 FabricJS 提供的各种形状之一。为了创建矩形,我们必须创建一个 fabric.Rect 类的实例并将其添加到画布。

strokeWidth 属性允许我们为对象指定描边的宽度。

语法

new fabric.Rect( { strokeWidth: Number }: Object)

参数

  • 选项(可选) - 此参数是一个对象,它为我们的矩形提供额外的自定义。使用此参数,可以更改与对象的许多属性相关的属性,其中strokeWidth 是一个属性,例如颜色、光标和描边宽度。

选项键

  • strokeWidth - 此属性接受一个数字,允许我们为对象指定描边的宽度。其默认值为 1。

示例 1

对象的描边的默认外观

让我们看一个代码示例,它描述了矩形对象的描边的默认外观。由于我们没有使用 strokeWidth 属性,因此呈现的是默认宽度。

<!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 appearance of an object’s stroke</h2>
   <p>You can see the default object width of the stroke around the rectangle.</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: 70,
         width: 170,
         height: 70,
         fill: "#f4f0ec",
         stroke: "#2a52be",
      });

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

示例 2

strokeWidth 属性作为键传递

在这个例子中,我们将strokeWidth 属性的值设置为 5。这将确保我们的矩形对象以宽度为 5 像素的描边呈现。

<!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 strokeWidth property as key</h2>
   <p>You can now see that the stroke width is 5px wide around the rectangle.</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: 70,
         width: 170,
         height: 70,
         fill: "#f4f0ec",
         stroke: "#2a52be",
         strokeWidth: 5,
      });

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

更新于:2022年6月30日

399 次浏览

启动您的职业生涯

完成课程获得认证

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