如何使用 FabricJS 建立影像物件的 JSON 表示?


在本教程中,我們將學習如何使用 FabricJS 建立影像物件的 JSON 表示。我們可以透過建立 fabric.Image 的例項來建立影像物件。由於它是 FabricJS 的基本元素之一,我們還可以透過應用角度、不透明度等屬性輕鬆自定義它。為了建立影像物件的 JSON 表示,我們使用 toJSON 方法。

語法

toJSON(propertiesToInclude: Array): Object

引數

  • propertiesToInclude − 此引數接受一個包含我們可能希望在輸出中額外包含的任何屬性的 陣列。此引數是可選的。

使用 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 image instance </p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.tw/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 110, }); // Add it to the canvas canvas.add(image); // Using the toJSON method console.log( "JSON representation of the Image instance is: ", image.toJSON() ); </script> </body> </html>

使用 toJSON 方法新增其他屬性

示例

讓我們看一個程式碼示例,以瞭解如何使用 toJSON 方法包含其他屬性。在這種情況下,我們添加了一個名為“name”的自定義屬性。我們可以將特定屬性作為選項物件的第二個引數傳遞給 fabric.Image 例項,並將相同的鍵傳遞給 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 added property called name </p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.tw/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object with name key // passed in options object var image = new fabric.Image(imageElement, { top: 50, left: 110, name: "Image instance", }); // Add it to the canvas canvas.add(image); // Using the toJSON method console.log( "JSON representation of the Image instance is: ", image.toJSON(["name"]) ); </script> </body> </html>

結論

在本教程中,我們使用兩個示例演示瞭如何使用 FabricJS 建立影像物件的 JSON 表示。

更新於: 2022年10月26日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告