如何使用 FabricJS 建立線條物件的 Object 表示?


在本教程中,我們將學習如何使用 FabricJS 建立線條物件的 Object 表示。線條元素是 FabricJS 提供的基本元素之一,用於建立直線。因為線條元素在幾何上是一維的,並且不包含內部,所以它們永遠不會被填充。我們可以透過建立`fabric.Line`的例項,指定線條的x和y座標,並將其新增到畫布上來建立一個線條物件。為了建立線條物件的 Object 表示,我們使用`toObject`方法。

語法

toObject(propertiesToInclude: Array): fabric.Object

引數

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

使用`toObject`方法

示例

讓我們來看一個程式碼示例,看看使用`toObject`方法時的日誌輸出。在這種情況下,將返回線條例項的 Object 表示。

<!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 toObject method</h2> <p> You can open console from dev tools and see that the logged output contains the Object 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 toObject method console.log("Object representation of the Line instance is: ", line.toObject()); </script> </body> </html>

使用`toObject`方法新增附加屬性

示例

讓我們來看一個程式碼示例,看看如何使用`toObject`方法包含附加屬性。在這種情況下,我們添加了一個名為“PropertyName”的自定義屬性。我們可以將特定屬性作為第二個引數傳遞給`fabric.Line`例項中的options物件,並將相同的鍵傳遞給`toObject`方法。

<!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 toObject method to add additional properties</h2> <p> You can open console from dev tools and see that the logged output contains added property called PropertyName </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 PropertyName key // passed in options object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, PropertyName: "property", }); // Add it to the canvas canvas.add(line); // Using the toObject method console.log( "Object representation of the Line instance is: ", line.toObject(["PropertyName"]) ); </script> </body> </html>

更新於:2022年10月21日

瀏覽量 152

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.