使用 FabricJS 将 Polygon 对象转换为类似数据的 URL 字符串
我们可以通过创建 fabric.Polygon 实例来创建 Polygon 对象。多边形对象的特征是任何由一组连接的直线段组成的封闭形状。由于它是 FabricJS 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松地对其进行自定义。
为了将 Polygon 对象转换为类似数据的 URL 字符串,我们使用 toDataURL 方法。此方法将对象转换为类似数据的 URL 字符串。
语法
toDataURL(options: Object): String
参数
options (可选) − 此参数是一个 Object,它为 Polygon 对象的 URL 表示提供额外的自定义。使用此参数格式,可以更改质量、乘数和许多其他属性。
示例 1:不使用 toDataURL 方法的默认值
让我们看一个代码示例,看看当不使用 toDataURL 方法时 Polygon 对象是什么样子。使用 toDataURL 方法时,将返回 Polygon 对象的 URL 表示。在这个例子中,我们创建了一个 Polygon 对象并为其分配了各种属性,如描边、填充等。但是,由于我们没有使用 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>
// 初始化一个画布实例
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// 初始化一个多边形对象
var poly = 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",
}
);
// 将其添加到画布
canvas.add(polygon);
// 控制台记录 Polygon 对象
console.log("The Polygon object is as follows: ", polygon);
</script>
</body>
</html>
示例 2:使用 toDataURL 方法
让我们看一个代码示例,以查看使用 toDataURL 方法时记录的输出。一旦我们从开发工具打开控制台,我们就可以看到 Polygon 对象的 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>
// 初始化一个画布实例
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// 初始化一个多边形对象
var poly = 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",
}
);
// 将其添加到画布
canvas.add(polygon);
// 使用 toDataURL 方法
console.log(polygon.toDataURL());
</script>
</body>
</html>
结论
在本教程中,我们使用了两个简单示例来演示如何使用 FabricJS 将多边形对象转换为类似数据的 URL 字符串。
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

