使用 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