如何在 FabricJS 中将折线 (Polyline) 对象序列化为 JSON?


折线对象可以由一组连接的直线段来表征。由于它是 FabricJS 的基本元素之一,因此我们也可以通过应用角度、不透明度等属性来轻松自定义它。

序列化是指将画布转换为可保存的数据,这些数据以后可以转换回画布。此数据可以是对象或 JSON,以便可以将其存储在服务器上。我们将使用toJSON()方法将包含折线对象的画布转换为 JSON。

语法

toJSON(propertiesToInclude: Array): Object

参数

  • propertiesToInclude − 此参数接受一个数组,其中包含我们可能希望在输出中额外包含的任何属性。此参数是可选的。

示例 1:使用 toJSON 方法

让我们看一个代码示例,以查看使用toJSON方法时记录的输出。在这种情况下,将返回折线实例的 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>

更新于: 2023年2月16日

251 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.