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


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

語法

toObject(propertiesToInclude: Array): Object

引數

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

使用 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 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 toObject method console.log( "Object representation of the Image instance is: ", image.toObject() ); </script> </body> </html>

使用 toObject 方法新增其他屬性

示例

讓我們看一個程式碼示例,以瞭解如何使用 toObject 方法包含其他屬性。在這種情況下,我們添加了一個名為“PropertyName”的自定義屬性。我們可以將特定屬性作為第二個引數傳遞給 fabric.Image 例項中的選項物件,並將相同的鍵傳遞給 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> <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 PropertyName key // passed in options object var image = new fabric.Image(imageElement, { top: 50, left: 110, PropertyName: "property", }); // Add it to the canvas canvas.add(image); // Using the toObject method console.log( "Object representation of the Image instance is: ", image.toObject(["PropertyName"]) ); </script> </body> </html>

結論

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

更新於: 2022-10-26

245 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.