如何在 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 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告