如何使用 FabricJS 停用文字框的居中縮放?


在本教程中,我們將學習如何使用 FabricJS 停用文字框的居中縮放。我們可以自定義、拉伸或移動文字框中的文字。為了建立文字框,我們必須建立一個`fabric.Textbox`類的例項並將其新增到畫布中。當透過控制元件進行縮放時,為`centeredScaling`屬性賦值為`true`,則使用中心作為物件的變換原點。

語法

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

引數

  • text − 此引數接受一個字串,即我們想要在文字框中顯示的文字字串。

  • options (可選) − 此引數是一個物件,它為我們的文字框提供額外的自定義選項。使用此引數,可以更改與物件相關的許多屬性,其中`centeredScaling`就是一個屬性,例如顏色、游標、描邊寬度等。

選項鍵

  • centeredScaling − 此屬性接受布林值,並允許我們控制物件是否應使用其中心作為其變換原點。

示例 1

 centeredScaling作為鍵併為其賦值“true”

讓我們來看一個程式碼示例,看看當啟用centeredScaling屬性時文字框物件的行為。當我們放大物件時,變換原點是文字框的中心。

<!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 centeredScaling as key and assigning a "true" value to it</h2>
   <p>Try scaling the textbox to see that centered scaling has been enabled</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("Success is the child of audacity.", {
         backgroundColor: "#ffe5b4",
         width: 400,
         top: 70,
         left: 110,
         centeredScaling: true,
      });

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

示例 2

停用 centeredScaling 屬性

我們可以透過為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>Disabling centeredScaling property</h2>
   <p>Try scaling the textbox to see that centered scaling has been disabled</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("Success is the child of audacity.", {
         backgroundColor: "#ffe5b4",
         width: 400,
         top: 70,
         left: 110,
         centeredScaling: false,
      });

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

更新於:2022年7月29日

304 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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