如何使用 FabricJS 更改 IText 的字型粗細?


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

然而,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說並不適用,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。字型粗細是指決定文字顯示粗細的數值。我們可以使用 `fontWeight` 屬性更改字型粗細。

語法

new fabric.IText(text: String , { fontWeight: Number|String }: Object)

引數

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

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

選項鍵

  • fontWeight − 此屬性接受一個數字字串值,它決定了 IText 物件內文字的粗細。其預設值為 normal。

示例 1

將 fontWeight 屬性作為鍵,並使用數值

讓我們來看一個程式碼示例,瞭解當使用數值作為 fontWeight 屬性的值時,IText 物件將如何顯示。在本例中,我們將其值設定為 400,這意味著我們的文字將具有普通字型。我們也可以使用其他值,例如 600 或 800。

<!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 fontWeight property as key with a numerical value</h2> <p>You can see that the text is of normal font</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: 60, top: 70, fill: "#6abfe1", fontWeight: 400, } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

將 fontWeight 屬性作為鍵,並使用 “bold” 作為值

在這個例子中,我們將 fontWeight 屬性作為鍵,其值為 “bold”。這意味著我們的 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 fontWeight property as key with the value as “bold”</h2> <p>You can see that the IText object has been rendered with bold text</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: 60, top: 70, fill: "#6abfe1", fontWeight: "bold", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新於: 2022年9月12日

329 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告