使用 FabricJS 設定文字行背景顏色


在本教程中,我們將學習如何使用 FabricJS 設定文字行的背景顏色。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字修飾、行高,這些功能分別可以透過 textAlign、underline 和 lineHeight 屬性獲得。同樣,我們也可以使用 textBackgroundColor 屬性設定文字行的背景顏色。

語法

new fabric.Text(text: String , { textBackgroundColor : String }: Object)

引數

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

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

選項鍵

  • textBackgroundColor − 此屬性接受一個字串值,允許我們設定文字行的背景顏色。

示例 1

使用十六進位制值作為 textBackgroundColor 屬性的鍵

讓我們來看一個程式碼示例,使用十六進位制顏色值來為我們的三角形物件分配背景顏色。在這個例子中,我們使用了十六進位制顏色程式碼 #ebdef0,它是一種淡紫色。

<!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 textBackgroundColor property as key with a hexadecimal value</h2> <p>You can see the background colour of the text lines</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: 60, top: 70, fill: "green", textBackgroundColor: "#ebdef0" }); // Add it to the canvas canvas.add(text); </script> </body> </html>

示例 2

使用 rgba 值作為 textBackgroundColor 屬性的鍵

我們可以使用 RGBA 值而不是十六進位制顏色程式碼,它代表:紅色、綠色、藍色和 alpha。alpha 引數指定顏色的不透明度。在這個例子中,我們使用了 rgba 值 (255,20,147,0.8),它是一種具有 0.8 不透明度的粉紅色。

<!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 textBackgroundColor property as key with a RGBA value</h2> <p>You can see the new background colour of the text lines</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: 60, top: 70, fill: "green", textBackgroundColor: "rgba(255,20,147,0.2)" }); // Add it to the canvas canvas.add(text); </script> </body> </html>

更新於:2022年9月14日

248 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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