使用FabricJS缩放时如何保持椭圆的描边宽度?


在本教程中,我们将学习如何使用FabricJS在缩放时保持椭圆的描边宽度。默认情况下,描边宽度会根据对象的缩放值进行增减。但是,我们可以使用`strokeUniform`属性禁用此行为。

语法

new fabric.Ellipse({ strokeUniform: Boolean }: Object)

参数

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

选项键

  • strokeUniform − 此属性接受一个布尔值,允许我们指定描边宽度是否会随对象一起缩放。其默认值为**false**。

示例1

缩放对象时描边宽度的默认外观

下面的示例描述了正在缩放的椭圆对象的描边宽度的默认外观。由于我们没有使用`strokeUniform`属性,因此描边宽度也会受到对象缩放的影响。

<!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>How to maintain stroke width of Ellipse while scaling using FabricJS?</h2>
      <p>Select the object and stretch it horizontally or vertically. Here the stroke width will get affected while scaling the object up or down. This is the default behavior. Here we have not used the <b>strokeUniform</b> property. </p>
      <canvas id="canvas"></canvas>
     
      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");

         // Initiate an ellipse instance
         var ellipse = new fabric.Ellipse({
            left: 215,
            top: 100,
            fill: "blue",
            rx: 90,
            ry: 50,
            stroke: "#c154c1",
            strokeWidth: 15,
         });
         canvas.add(ellipse);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

示例2

strokeUniform属性作为键传递

在此示例中,我们将`strokeUniform`属性作为键传递。因此,对象的描边将不再随对象的缩放而增减。在此示例中,`strokeUniform`属性已赋值为“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>Maintaining the stroke width of an Ellipse while scaling using FabricJS</h2>
      <p>Select the object and stretch it in any direction. Here the stroke width of the ellipse will remain unaffected at the time of scaling up because we have applied the <b>strokeUniform</b> property. </p>
      <canvas id="canvas"></canvas>

      <script>
         // Initiate a canvas instance
         var canvas = new fabric.Canvas("canvas");

         // Initiate an ellipse instance
         var ellipse = new fabric.Ellipse({
            left: 215,
            top: 100,
            fill: "blue",
            rx: 90,
            ry: 50,
            stroke: "#c154c1",
            strokeWidth: 15,
            strokeUniform: true,
         });

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

更新于:2022年5月24日

385 次浏览

开启你的职业生涯

完成课程获得认证

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