如何使用 FabricJS 建立帶有背景顏色的文字框?
在本教程中,我們將使用 FabricJs 建立一個帶有背景顏色的文字框。我們可以自定義、拉伸或移動文字框中編寫的文字。我們還可以使用諸如fontSize、fontFamily、fontStyle、fontWeight等屬性來自定義文字本身。為了建立文字框,我們將必須建立一個fabric.Textbox類的例項並將其新增到畫布中。backgroundColor 屬性允許我們將顏色分配給物件的背景,對於文字框,它呈矩形。
語法
new fabric.Textbox(text: String, { backgroundColor: String }: Object)引數
text − 此引數接受一個字串,即我們想要在文字框內顯示的文字字串。
options(可選)− 此引數是一個物件,它為我們的文字框提供額外的自定義選項。使用此引數,可以更改與文字框相關的許多屬性,例如顏色、游標、筆觸寬度等,其中backgroundColor是一個屬性。
選項鍵
backgroundColor − 此屬性接受一個字串值,用於確定背景顏色。
示例 1
將 backgroundColor 屬性作為鍵傳遞,並使用十六進位制值
讓我們來看一個程式碼示例,使用顏色的十六進位制值將背景顏色分配給我們的 Textbox 物件。在本例中,我們使用了十六進位制顏色程式碼“#ffe4e1”,這是一種非常淺的紅色。
<!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 backgroundColor property as key with a hexadecimal value</h2>
<p>You can see that the background colour is a very light shade of red.</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("Details matter, it's worth waiting to get it right.", {
backgroundColor: "#ffe4e1",
width: 400,
top: 70,
left: 110,
});
// Add it to the canvas
canvas.add(textbox);
</script>
</body>
</html>示例 2
將 backgroundColor 屬性作為鍵傳遞,並使用 rgba 值
我們可以使用 RGBA 值而不是十六進位制顏色程式碼,它代表紅色、綠色、藍色和 alpha。alpha 引數指定顏色的不透明度。在本例中,我們使用了 rgba 值 (0,206,209,0.4),它是深綠松石色,不透明度為 0.4。
<!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 backgroundColor property as key with an RGBA value</h2>
<p>You can see that the background colour is a dark turquoise colour with 0.4 opacity.</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("Details matter, it's worth waiting to get it right.", {
backgroundColor: "rgba(0,206,209, 0.4)",
width: 400,
top: 70,
left: 110,
});
// Add it to the canvas
canvas.add(textbox);
</script>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP