如何使用 FabricJS 透過角點非均勻地調整物件大小?


在本文中,我們將學習如何使用 FabricJS 透過角點非均勻地調整物件大小。在 FabricJS 中,從角點拖動時,物件會按比例變換。但是,我們可以透過按 uniScaleKey 來控制此行為。

語法

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

引數

  • element − 此引數是<canvas> 元素本身,可以使用 Document.getElementById() 或<canvas> 元素的 ID 來獲取。FabricJS 畫布將在此元素上初始化。

  • options (可選) − 此引數是一個物件,它為我們的畫布提供額外的自定義選項。使用此引數,可以更改與畫布相關的許多屬性,例如顏色、游標、邊框寬度以及 uniScaleKey 屬性。它接受一個字串值,該值指示哪個鍵切換統一縮放。它的預設值是shiftKey。可能的鍵值是:altKey,shiftKeyctrlKey。

示例 1

按 shiftKey 停用統一縮放

當在保持縱橫比的同時透過拖動邊緣來變換物件時,我們稱該物件被均勻縮放。uniScaleKey 允許我們當場控制該行為。預設情況下,FabricJS 中的物件按比例縮放。讓我們看一個程式碼示例,說明在按下 shiftKey 時物件如何進行非均勻縮放。

<!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>Resizing an object non-uniformly via corner points</h2>
   <p>Hold the <b>shift</b> key and drag the object from its corners. The object will resize non-uniformly. </p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      // Creating an instance of the fabric.Rect class
      var circle = new fabric.Circle({
         left: 70,
         top: 90,
         radius: 40,
         fill: "#006400",
      });
      // Adding it to the canvas
      canvas.add(circle);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

示例 2

將 uniScaleKey 的值更改為 ctrlKey

雖然其預設值是shiftKey,但我們也可以使用'ctrlKey'和'altKey'。如果指定 NULL 或任何其他鍵,則此功能將被停用。

<!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>Resizing an object non-uniformly via corner points</h2>
   <p>Hold the <b>ctrl</b> key and drag the object from its corners. The object will resize non-uniformly. </p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         uniScaleKey: "ctrlKey",
      });
      // Creating an instance of the fabric.Rect class
      var circle = new fabric.Circle({
         left: 70,
         top: 90,
         radius: 40,
         fill: "#006400",
      });
      // Adding it to the canvas
      canvas.add(circle);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

更新於:2022年5月19日

752 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.