如何使用 FabricJS 設定 IText 變換的垂直原點?


在本教程中,我們將學習如何使用 FabricJS 設定 IText 變換的垂直原點。IText 類是在 FabricJS 1.4 版本中引入的,它擴充套件了 fabric.Text 並用於建立 IText 例項。IText 例項使我們可以自由地選擇、剪下、貼上或新增新文字,無需額外的配置。還支援各種按鍵組合和滑鼠/觸控組合,使文字具有互動性,而 Text 中沒有提供這些功能。

然而,基於 IText 的文字框允許我們調整文字矩形的尺寸並自動換行。這對於 IText 來說並不適用,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們也可以使用 originY 屬性設定變換的垂直原點。

語法

new fabric.IText(text: String , { originY : String }: Object)

引數

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

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

選項鍵

  • originY − 此屬性接受一個字串值,允許我們設定變換的垂直原點。可能的值為“top”、“bottom”和“center”。其預設值為“top”。

示例 1

IText 物件的預設外觀

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

<!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 IText 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 an itext object var itext = new fabric.IText( "Add sample text here.
Lorem ipsum dolor sit amet"
,{ width: 300, left: 210, top: 70, fill: "#e75c22", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

將 originY 屬性作為鍵傳遞值

在這個示例中,我們將看到為 originY 屬性賦值如何改變變換的垂直原點。我們在本示例中使用了兩個 IText 物件來顯示差異。在我們的第一個 IText 物件中,由於我們傳遞的值為“bottom”,因此變換的垂直原點現在位於底部。相同的頂部屬性 70 應用於兩個 IText 物件,但由於變換的垂直原點發生變化,它們仍然位於不同的垂直位置。

<!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 the origin of transformation for the first IText object(itext1) is bottom while IText2 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 an itext object var itext1 = new fabric.IText("First IText object", { width: 300, left: 310, top: 70, fill: "#e75c22", originY: "bottom", }); // Initiate another itext object var itext2 = new fabric.IText("Second IText object", { width: 300, left: 310, top: 70, fill: "#22e75c", }); // Add both to the canvas canvas.add(itext1); canvas.add(itext2); </script> </body> </html>

更新於:2022年9月13日

135 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告