如何使用 FabricJS 更改文字框的字型粗細?
在本教程中,我們將瞭解如何使用 FabricJS 更改文字框的字型粗細。我們可以自定義、拉伸或移動文字框中的文字。為了建立文字框,我們需要建立一個 fabric.Textbox 類的例項並將其新增到畫布中。字型粗細指的是決定文字顯示為粗體或細體的值。
語法
new fabric.Textbox(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 textbox object
var textbox = new fabric.Textbox("Solitary trees, if they grow at all, grow strong.", {
backgroundColor: "#fff8dc",
width: 400,
left: 50,
top: 70,
fill: "#cf3476",
fontWeight: 400,
});
// Add it to the canvas
canvas.add(textbox);
</script>
</body>
</html>示例 2
使用 "bold" 作為 fontWeight 屬性的值
在本示例中,我們將 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 textbox 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 textbox object
var textbox = new fabric.Textbox("Solitary trees, if they grow at all, grow strong", {
backgroundColor: "#fff8dc",
width: 400,
left: 50,
top: 70,
fill: "#cf3476",
fontWeight: "bold",
});
// Add it to the canvas
canvas.add(textbox);
</script>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP