如何使用 FabricJS 設定 IText 文字行的背景顏色?
在本教程中,我們將學習如何使用 FabricJS 設定 IText 文字行的背景顏色。IText 類是在 FabricJS 1.4 版本中引入的,它擴充套件了 fabric.Text 並用於建立 IText 例項。IText 例項使我們能夠自由地選擇、剪下、貼上或新增新文字,而無需額外的配置。還支援各種鍵盤組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中沒有提供。但是,Textbox 基於 IText,允許我們調整文字矩形的大小並自動換行。這對於 IText 來說是不正確的,因為高度不會根據行的換行進行調整。我們可以使用各種屬性來操作 IText 物件。類似地,我們還可以使用 textBackgroundColor 屬性設定 IText 文字行的背景顏色。
語法
new fabric.IText(text: String , { textBackgroundColor : String }: Object)
引數
text − 此引數接受一個字串,即我們要顯示的文字字串。
options(可選) − 此引數是一個物件,它為我們的物件提供額外的自定義。使用此引數,可以更改與物件相關的顏色、游標、邊框寬度以及許多其他屬性,其中 textBackgroundColor 是一個屬性。
選項鍵
textBackgroundColor − 此屬性接受一個字串值,允許我們設定文字行的背景顏色。
示例 1
IText 物件的預設外觀
讓我們看一個程式碼示例,看看當不使用 textBackgroundColor 屬性時,IText 物件是什麼樣子。在這種情況下,我們的 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 the IText object does not contain text background colour</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: 210, top: 70, fill: "#d755da", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>
示例 2
將 textBackgroundColor 屬性作為鍵傳遞並帶有值
在這個例子中,我們將看到如何為 textBackgroundColor 屬性賦值來為文字行建立背景顏色。由於我們將其值設定為“黑色”,因此 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 textBackgroundColor property as key with a value</h2> <p>You can see that the IText object contains text background colour</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: 210, top: 70, fill: "#d755da", textBackgroundColor: "black", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP