使用 FabricJS 將多邊形物件轉換為類似資料的 URL 字串
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表徵。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。
為了將多邊形物件轉換為類似資料的 URL 字串,我們使用toDataURL方法。此方法將物件轉換為類似資料的 URL 字串。
語法
toDataURL(options: Object): String
引數
options (可選) − 此引數是一個物件,它為多邊形物件的 URL 表示提供額外的自定義。使用此引數格式,可以更改質量、乘數和許多其他屬性。
示例 1:不使用 toDataURL 方法時的預設值
讓我們來看一個程式碼示例,看看在不使用toDataURL方法時多邊形物件是什麼樣子。使用toDataURL方法時,將返回多邊形物件的 URL 表示。在這個例子中,我們建立了一個多邊形物件併為其分配了各種屬性,例如筆觸、填充等。但是,由於我們沒有使用toDataURL方法,因此我們不會在控制檯中看到物件的 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>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);
// Initiating a polygon object
var polygon = new fabric.Polygon(
[
{ x: -20, y: -35 },
{ x: 20, y: -35 },
{ x: 40, y: 0 },
{ x: 20, y: 35 },
{ x: -20, y: 35 },
{ x: -40, y: 0 },
],
{
stroke: "red",
left: 100,
top: 50,
fill: "black",
strokeWidth: 2,
strokeLineJoin: "bevil",
}
);
// Adding it to the canvas
canvas.add(polygon);
// Console logging the Polygon object
console.log("The Polygon object is as follows: ", polygon);
</script>
</body>
</html>
示例 2:使用 toDataURL 方法
讓我們來看一個程式碼示例,看看使用toDataURL方法時的日誌輸出。一旦我們從開發者工具中開啟控制檯,我們就可以看到多邊形物件的 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 the final 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);
// Initiating a polygon object
var polygon = new fabric.Polygon(
[
{ x: -20, y: -35 },
{ x: 20, y: -35 },
{ x: 40, y: 0 },
{ x: 20, y: 35 },
{ x: -20, y: 35 },
{ x: -40, y: 0 },
],
{
stroke: "red",
left: 100,
top: 50,
fill: "black",
strokeWidth: 2,
strokeLineJoin: "bevil",
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the toDataURL method
console.log(polygon.toDataURL());
</script>
</body>
</html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 將多邊形物件轉換為類似資料的 URL 字串。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP