如何在使用 FabricJS 的画布上启用居中缩放?


在本文中,我们将学习如何在使用 FabricJS 的画布上启用居中缩放。在 FabricJS 中,从角拖动对象时,对象会按比例变换。我们可以使用 `centeredScaling` 属性以中心作为变换的原点。

语法

new fabric.Canvas(element: HTMLElement|String, { centeredScaling: Boolean }: Object)

参数

  • element − 此参数是<canvas> 元素本身,可以使用 `Document.getElementById()` 或<canvas> 元素本身的 ID 获取。FabricJS 画布将在此元素上初始化。

  • options (可选) − 此参数是一个对象,它为我们的画布提供额外的自定义选项。使用此参数可以更改与画布相关的颜色、光标、边框宽度和许多其他属性,其中 `centeredScaling` 是一个属性。它接受一个布尔值,该值决定对象是否应使用中心点作为变换的原点。其默认值为 False。

示例 1

将 `centeredScaling` 键的值设置为 false

让我们来看一个代码示例,说明当 `centeredScaling` 设置为 False 时对象如何缩放。

<!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>Enabling centered scaling in canvas using FabricJS</h2>
   <p>Select the object and try to resize it by its corners. The object will scale non-uniformly from its center.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         centeredScaling: false
      });
      // Creating an instance of the fabric.Rect class
      var circle = new fabric.Circle({
         left: 200,
         top: 100,
         radius: 40,
         fill: "blue",
      });
      // Adding it to the canvas
      canvas.add(circle);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

示例 2

将 `centeredScaling` 键的值设置为 True

默认情况下,centeredScaling 键设置为 False。因此,我们需要将此键传递给类并将其值赋值为 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>Enabling centered scaling in canvas using FabricJS</h2>
   <p>Here we have set <b>centeredScaling</b> to True. Select the object and try to resize it by its corners. The object will scale uniformly from its center. </p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         centeredScaling: true
      });
      // Creating an instance of the fabric.Rect class
      var circle = new fabric.Circle({
         left: 200,
         top: 100,
         radius: 40,
         fill: "blue",
      });
      // Adding it to the canvas
      canvas.add(circle);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

更新于: 2022年5月19日

847 次浏览

开启你的职业生涯

完成课程获得认证

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