如何在 FabricJS 中為 IText 新增描邊?
在本教程中,我們將學習如何在 FabricJS 中為 IText 新增描邊。IText 類在 FabricJS 1.4 版本中引入,繼承自 fabric.Text,用於建立 IText 例項。IText 例項使我們可以自由地選擇、剪下、貼上或新增新文字,無需額外的配置。它還支援各種鍵盤組合和滑鼠/觸控組合,使文字具有互動性,而 Text 類則不具備這些功能。
然而,基於 IText 的文字框允許我們調整文字矩形的尺寸並自動換行。這對於 IText 來說並不適用,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 stroke 屬性新增描邊。
語法
new fabric.IText(text: String, { stroke: String }: Object)
引數
text − 此引數接受一個字串,即我們要顯示的文字字串。
options (可選) − 此引數是一個物件,它為我們的 IText 物件提供額外的自定義選項。使用此引數可以更改與物件相關的顏色、游標、描邊寬度以及許多其他屬性,其中描邊是一個屬性。
選項鍵
stroke: − 此屬性接受一個字串,它確定該物件邊框的顏色。
示例 1
使用十六進位制值作為 stroke 屬性鍵
讓我們來看一個程式碼示例,瞭解當使用 stroke 屬性時 IText 物件的外觀。十六進位制顏色程式碼以 # 開頭,後面跟著六位數字,表示一種顏色。在本例中,我們使用了“#097969”,它是綠色。
<!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 stroke property as key with a hexadecimal value</h2> <p>You can see that the stroke around the text is of green 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
consectetur adipiscing.",{ width: 300, left: 50, top: 70, fill: "white", stroke: "#097969", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>
示例 2
將 rgba 值傳遞給 stroke 屬性
在本例中,我們將看到如何為 stroke 屬性賦值 rgba 值。我們可以使用RGBA值代替十六進位制顏色程式碼,它代表:紅色、綠色、藍色和 alpha。alpha 引數指定顏色的不透明度。在本例中,我們傳遞了 rgba 值為 rgba(255,11,15,1),它是紅色,不透明度為 1。
<!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 an rgba value to the stroke property</h2> <p>You can see that the stroke around the text is of red 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
consectetur adipiscing.",{ width: 300, left: 50, top: 70, fill: "white", stroke: "rgba(255,11,15,1)", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP