如何将Polyline对象序列化为JSON在FabricJS中
折线对象可以由一组相连的直线段来表示。由于它是FabricJS的基本元素之一,我们还可以轻松地通过应用属性如角度、不透明度等来定制它。
序列化意味着将画布转换为可保存的数据,稍后可以将其转换回画布。这些数据可以是对象或JSON格式,以便可以存储在服务器上。我们将使用toJSON()方法将带有Polyline对象的画布转换为JSON。
语法
toJSON(propertiesToInclude: Array): Object
参数
- _ propertiesToInclude_ - 此参数接受一个 Array ,其中包含我们可能想要在输出中额外包含的任何属性。此参数是可选的。
示例1:使用toJSON方法
让我们看一个代码示例,当使用 toJSON 方法时,输出将被记录。在这种情况下,将返回Polyline实例的JSON表示。
<!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 toJSON method</h2>
<p> You can open console from dev tools and see that the logged output contains the JSON representation of the Polyline instance </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 Polyline instance
var polyLine = new fabric.Polyline([
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 100 },
{ x: 350, y: 60 },
], {
stroke: "orange",
fill: "white",
strokeWidth: 5,
});
// Add it to the canvas
canvas.add(polyLine);
// Using the toJSON method
console.log("JSON representation of the Polyline instance is: ", polyLine.toJSON());
</script>
</body>
</html>
示例2:使用toJSON方法添加额外属性
让我们来看一个代码示例,看看我们如何使用toJSON方法通过添加额外属性。在这种情况下,我们添加了一个名为“name”的自定义属性。我们可以将特定属性作为选项对象的第二个参数传递给fabric.Polyline实例,并将相同的键传递给toJSON方法。
<!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 toJSON method to add additional properties</h2>
<p> You can open console from dev tools and see that the logged output contains JSON with the added property called name </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 Polyline object with name key
// passed in options object
var polyLine = new fabric.Polyline([
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 100 },
{ x: 350, y: 60 },
], {
stroke: "orange",
fill: "white",
strokeWidth: 5,
name: "Polyline instance",
});
// Add it to the canvas
canvas.add(polyLine);
// Using the toJSON method
console.log(
"JSON representation of the Polyline instance is: ", polyLine.toJSON(["name"])
);
</script>
</body>
</html>