如何在使用 FabricJS 時設定文字框中文字的對齊方式?
在本教程中,我們將學習如何在使用 FabricJS 時設定文字框中文字的對齊方式。我們可以自定義、拉伸或移動文字框中編寫的文字。為了建立文字框,我們必須建立一個`fabric.Textbox`類的例項並將其新增到畫布。同樣,我們也可以使用`textAlign`屬性設定其文字對齊方式。
語法
new fabric.Textbox(text: String, { textAlign : String }: Object)
引數
text − 此引數接受一個字串,即我們想要在文字框內顯示的文字字串。
options (可選) − 此引數是一個物件,它為我們的文字框提供額外的自定義選項。使用此引數,可以更改與物件相關的許多屬性,例如顏色、游標、邊框寬度等等,其中`textAlign`也是一個屬性。
選項鍵
textAlign − 此屬性接受一個字串作為值,允許我們控制文字對齊的可能值。其預設值為左對齊。其他可能的值為“center”(居中),“right”(右對齊),“justify”(兩端對齊),“justify-left”(左端對齊),“justify-center”(居中對齊)和“justify-right”(右端對齊),其解釋如下:
center − 將文字居中對齊
right − 將文字右對齊
justify − 拉伸文字行,使每一行與文字框的左右邊緣距離相等
justify-left − 拉伸文字行,使每一行與文字框的左邊緣距離相等
justify-center − 將每一行居中,與文字框的左右邊緣距離不等
justify-right − 拉伸文字行,使每一行與文字框的右邊緣距離相等
示例 1
文字框物件中文字的預設外觀
讓我們來看一個程式碼示例,看看當不使用`textAlign`屬性時文字框物件是什麼樣子。在這種情況下,我們的文字將左對齊。
<!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 in Textbox object</h2> <p>You can see that the text alignment is towards left</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("If you're too open-minded; your brains will fall out.", { width: 400, left: 50, top: 30, fill: "orange", strokeWidth: 2, stroke: "green", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
示例 2
將textAlign屬性作為鍵值對傳遞
在這個例子中,我們將看到為`textAlign`屬性賦值是如何改變畫布中文字框物件內文字對齊方式的。由於我們傳遞的值為“right”,因此文字現在將右對齊。
<!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 textAlign property as key with a value</h2> <p>You can see that the text alignment is towards right</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("If you're too open-minded; your brains will fall out.", { width: 400, left: 50, top: 70, fill: "orange", strokeWidth: 2, stroke: "green", textAlign: "right", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>