如何在 FabricJS 中為 IText 新增下劃線?


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

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

語法

new fabric.IText(text: String , { underline: Boolean }: Object)

引數

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

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

選項鍵

  • underline − 此屬性接受一個布林值,允許我們為文字新增下劃線。

示例 1

IText 物件的預設外觀

讓我們來看一個程式碼示例,看看當不使用 underline 屬性時,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>Default appearance of the IText object</h2> <p>You can see that no text decoration underline is present</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: 50, top: 70, fill: "#d755da", textBackgroundColor: "black", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

將 underline 屬性作為鍵,值為 true

在這個例子中,我們將看到如何使用 underline 屬性新增文字修飾下劃線。underline 屬性接受布林值,因此我們傳遞了一個 true 值,這將為我們的文字新增下劃線。

<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 underline property as key with a true value</h2> <p>You can see that text decoration underline is present</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: 50, top: 70, fill: "#d755da", textBackgroundColor: "black", underline: true, } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新於:2022年9月12日

283 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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