如何使用 FabricJS 建立 Line 物件的 JSON 表示?
在本教程中,我們將學習如何使用 FabricJS 建立 Line 物件的 JSON 表示。Line 元素是 FabricJS 提供的基本元素之一,用於建立直線。由於線元素在幾何上是一維的並且不包含內部,因此它們永遠不會被填充。我們可以透過建立一個 fabric.Line 例項,指定線的 x 和 y 座標並將其新增到畫布上來建立線物件。為了建立 Line 物件的 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 line 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 Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Add it to the canvas canvas.add(line); // Using the toJSON method console.log("JSON representation of the Line instance is: ", line.toJSON()); </script> </body> </html>
使用 toJSON 方法新增附加屬性
示例
讓我們看一個程式碼示例,看看如何使用 toJSON 方法包含附加屬性。在這種情況下,我們添加了一個名為“name”的自定義屬性。我們可以將特定屬性作為第二個引數傳遞給 fabric.Line 例項中的 options 物件,並將相同的鍵傳遞給 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> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a Line object with name key // passed in options object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, name: "Line instance", }); // Add it to the canvas canvas.add(line); // Using the toJSON method console.log( "JSON representation of the Line instance is: ", line.toJSON(["name"]) ); </script> </body> </html>
廣告