如何使用 FabricJS 調整文字中單個字元的基線?


在本教程中,我們將學習如何使用 FabricJS 調整文字中單個字元的基線。我們可以透過新增 fabric.Text 的例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字裝飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。類似地,我們還可以使用 deltaY 屬性來調整單個字元的基線。

語法

new fabric.Text(text: String , { styles: { deltaY: Number}:Object }: Object)

引數

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

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

選項鍵

  • styles − 此屬性接受一個物件值,它允許我們為單個字元新增樣式。

  • deltaY − 此屬性接受一個數字值,它允許我們僅為樣式調整基線。

示例 1

僅將 styles 屬性作為鍵傳遞

在此示例中,我們可以看到如何使用 styles 屬性為字元新增單個樣式。正如我們在此示例中看到的,只有第 0 個字元的 fontSize 為 55,fontWeight 為粗體,fontStyle 為“斜體”。第一級屬性是行號,第二級屬性是字元號。這裡我們都使用 0,表示第一行和第一個字元。

<!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 styles property as key</h2> <p>You can see that the first character looks different now</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", styles: { 0: { 0: { fontSize: 55, fontWeight: "bold", fontStyle: "oblique", } } } }); // Add it to the canvas canvas.add(text); </script> </body> </html>

示例 2

將 styles 屬性作為鍵以及 deltaY 屬性一起傳遞

在此示例中,我們將看到如何使用 deltaY 屬性為字元新增不同的基線。在這種情況下,第一行中的第二個數字(第一個索引)由於指定了 deltaY,因此具有與相鄰字元不同的基線。

<!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 styles property as key along with deltaY property</h2> <p> You can see that the second number in the first line has a different baseline </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.
H2O"
, { width: 300, left: 50, top: 70, fill: "green", styles: { 1: { 0: { fontSize: 55, fontWeight: "bold", fill: "red", }, 1: { deltaY: 15, fill: "blue", }, 2: { fontSize: 55, fontWeight: "bold", fill: "red", }, }, }, }); // Add it to the canvas canvas.add(text); </script> </body> </html>

更新於: 2022-09-14

274 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告