如何使用 FabricJS 更改文字的字型粗細?
在本教程中,我們將學習如何使用 FabricJS 更改文字的字型粗細。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字修飾、行高,這些功能分別可以透過 textAlign、underline 和 lineHeight 屬性獲得。字型粗細指的是決定文字顯示粗細的數值。
語法
new fabric.Text(text: String , { fontWeight: Number|String }: Object)
引數
text − 此引數接受一個字串,即我們要顯示的文字字串。
options (可選) − 此引數是一個物件,它為我們的文字提供額外的自定義選項。使用此引數可以更改與物件相關的許多屬性,例如顏色、游標、描邊寬度,其中 fontWeight 就是一個屬性。
選項鍵
fontWeight − 此屬性接受一個數字或字串值,用於確定文字在文字中顯示的粗細。其預設值為 normal。
示例 1
將 fontWeight 屬性作為鍵,並使用數值作為值
讓我們來看一個程式碼示例,瞭解當使用數值作為 fontWeight 屬性的值時,我們的文字物件將如何顯示。在本例中,我們將值設定為 400,這意味著我們的文字將具有普通字型。我們也可以使用其他值,例如 600 或 800。
<!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 fontWeight property as key with a numerical value</h2> <p>You can see that the text is of normal font</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", { left: 50, top: 70, fontWeight: 400, }); // Add it to the canvas canvas.add(text); </script> </body> </html>
示例 2
將 fontWeight 屬性作為鍵,並使用“bold”作為值
在此示例中,我們將 fontWeight 屬性作為鍵,並使用“bold”作為值。這意味著我們的文字物件將呈現具有較粗字母的文字。
<!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 fontWeight property as key with the value as “bold”</h2> <p>You can see that the text object has been rendered with bold text</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", { left: 50, top: 70, fontWeight: “bold”, }); // Add it to the canvas canvas.add(text); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP