首頁 > web前端 > js教程 > 主體

如何使用FabricJS設定文字轉換的垂直原點?

王林
發布: 2023-08-24 19:49:08
轉載
1449 人瀏覽過

如何使用FabricJS設定文字轉換的垂直原點?

在本教學中,我們將學習如何使用 FabricJS 設定文字轉換的垂直原點。我們可以透過新增 Fabric.Text 的實例在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,而且還提供了附加功能,例如文字對齊、文字裝飾、行高,這些功能可以分別透過屬性 textAlign、underline 和 lineHeight 獲得。同樣,我們也可以使用originY屬性來設定變換的垂直原點。

文法

new fabric.Text(text: String , { originY : String }: Object)
登入後複製

參數

  • text - 此參數接受 String,這是我們要顯示的文字字串。

  • 選項(可選) - 此參數是一個物件,它為我們的文字提供額外的自訂。使用此參數,可以變更與 originY 為屬性的物件相關的顏色、遊標、邊框寬度和許多其他屬性。

選項鍵

  • originY - 這個屬性接受一個String值,它允許我們設定轉換的垂直原點。可能的值為“頂部”、“底部”和“中心”。它的預設值為“top”。

範例 1

文字物件的預設外觀

#讓我們來看一個程式碼範例,看看不使用 originY 屬性時文字物件的外觀。在這種情況下,變換的垂直原點將為頂部,這也是預設值。

<!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 the Text object</h2>
   <p>You can see that the vertical origin of transformation is towards top</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 text object
      var text = new fabric.Text("Add sample text here.", {
         width: 300,
         left: 50,
         top: 70,
         fill: "green",
      });

      // Add it to the canvas
      canvas.add(text);
   </script>
</body>
</html>
登入後複製

範例 2

將 originY 屬性作為鍵傳遞給值

#在此範例中,我們將看到為 originY 屬性指派值如何更改變換的垂直原點。我們在本例中使用了兩個文字物件來顯示差異。在我們的第一個文字物件中,由於我們將值傳遞為“bottom”,所以變換的垂直原點現在位於底部。相同的頂部屬性 100 應用於兩個文本,但由於轉換的垂直原點發生變化,它們仍然處於不同的垂直位置。

<!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 the originY property as key with a value</h2>
   <p>You can see that origin of transformation for the first text object(text1) is bottom while text2 maintains the default vertical origin of transformation</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 text object
      var text1 = new fabric.Text("Text 1", {
         width: 300,
         left: 200,
         top: 100,
         fill: "green",
         originY: "bottom",
      });

      // Initiate a text object
      var text2 = new fabric.Text("Text 2", {
         width: 300,
         left: 50,
         top: 100,
         fill: "red",
      });

      // Add it to the canvas
      canvas.add(text1);
      canvas.add(text2);
   </script>
</body>
</html>
登入後複製

以上是如何使用FabricJS設定文字轉換的垂直原點?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!