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


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

語法

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

引數

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

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

選項鍵

  • originY − 此屬性接受一個字串值,允許我們設定變換的垂直原點。“top”(頂部),“bottom”(底部)和“center”(中心)是可能的取值。其預設值為“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>

更新於: 2022年9月14日

247 次檢視

開啟你的職業生涯

完成課程獲得認證

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