在本教程中,我們將學習如何使用 FabricJS 將 IText 對象轉換為類似數據的 URL 字符串。 IText 類是在 FabricJS 版本 1.4 中引入的,它擴展了 Fabric.Text 并用于創建 IText 實例。 IText 實例使我們可以自由選擇、剪切、粘貼或添加新文本,而無需額外配置。還有各種支持的按鍵組合和鼠標/觸摸組合使文本具有交互性,而 Text 中未提供這些組合。
然而,基于 IText 的 Textbox 允許我們調整文本矩形的大小并自動換行。對于 IText 來說情況并非如此,因為高度不會根據換行進行調整。我們可以通過使用各種屬性來操作 IText 對象。同樣,我們可以使用 toDataURL 方法將 IText 對象轉換為類似數據的 URL 字符串。
語法
toDataURL(options: Object): String
登錄后復制
參數
options(可選) – 此參數是一個對象,它為 IText 對象的 URL 表示形式提供額外的自定義。使用此參數格式、質量、乘數和許多其他屬性都可以更改。
示例 1
不使用 toDataURL 方法的默認值
讓我們看一個代碼示例,看看不使用 toDataURL 方法時 IText 對象是什么樣子。使用 toDataURL 方法時,將返回 IText 對象的 URL 表示形式。在這個例子中,我們創建了一個 itext 對象并為其分配了各種屬性,如描邊、填充、陰影等。但是,由于我們沒有使用 toDataURL 方法,所以我們將無法在控制臺而不是 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 value without using toDataURL method</h2>
<p>You can open console from dev tools and see the logged output</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 shadow object
var shadow = new fabric.Shadow({
blur: 25,
color: "grey",
offsetX: 12,
offsetY: 15,
});
// 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: "#c70039",
backgroundColor: "#c1dfed",
stroke: "#c70039",
originX: "center",
shadow: shadow,
}
);
// Add it to the canvas
canvas.add(itext);
// Console logging the itext object
console.log("The itext object is as follows: ", itext);
</script>
</body>
</html>
登錄后復制
示例 2
使用 toDataURL 方法
讓我們看一個代碼示例,以查看使用 toDataURL 方法時記錄的輸出。一旦我們從開發工具打開控制臺,我們就可以看到 IText 對象的 URL 表示。我們可以復制該 URL 并將其粘貼到新選項卡的地址欄中以查看最終輸出。
<!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>Using the toDataURL method</h2>
<p> You can open console from dev tools and see the output URL. You can copy that and paste it in the address bar of a new tab to see that the image </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 shadow object
var shadow = new fabric.Shadow({
blur: 25,
color: "grey",
offsetX: 12,
offsetY: 15,
});
// 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: "#c70039",
backgroundColor: "#c1dfed",
stroke: "#c70039",
originX: "center",
shadow: shadow,
}
);
// Add it to the canvas
canvas.add(itext);
// Using the toDataURL method
console.log(itext.toDataURL());
</script>
</body>
</html>
登錄后復制
以上就是如何使用 FabricJS 將 IText 對象轉換為類似數據的 URL 字符串?的詳細內容,更多請關注www.92cms.cn其它相關文章!






