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


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

然而,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說是不正確的,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們也可以使用 deltaY 屬性來調整單個字元的基線。

語法

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

引數

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

  • options (可選) − 此引數是一個物件,它為我們的 IText 物件提供額外的自定義選項。使用此引數,可以更改與物件相關的顏色、游標、邊框寬度和許多其他屬性,其中 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 only 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 an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 310, top: 70, fill: "#9455da", styles: { 0: { 0: { fontSize: 55, fontWeight: "bold", fontStyle: "oblique", }, }, }, }); // Add it to the canvas canvas.add(itext); </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 second 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 an itext object var itext = new fabric.IText("Add sample text here.
H2O"
, { width: 300, left: 310, top: 70, fill: "#9455da", 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(itext); </script> </body> </html>

更新時間: 2022-09-13

139 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.