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


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

語法

toString(): String

使用 `toString` 方法

示例

讓我們來看一個程式碼示例,看看使用 `toString` 方法時記錄的輸出。在這種情況下,將返回影像例項的字串表示。

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

使用 `toString` 方法比較兩個不同的元素

示例

讓我們來看一個程式碼示例,看看如何透過檢視各自的字串表示來比較兩個物件。在這裡,我們初始化了一個影像例項和一個矩形例項。在每個例項上應用 `toString` 方法後,我們可以在控制檯中看到它們的字串表示。

<!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 toString method to compare two different elements</h2> <p> You can open console from dev tools and see that the logged output contains the String representation of the Image instance and the rectangle 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, }); // Initiate a Rectangle object var rect = new fabric.Rect({ stroke: "red", strokeWidth: 20, width: 20, height: 50, left: 460, top: 55, }); // Add them to the canvas canvas.add(image); canvas.add(rect); // Using the toString method console.log( "String representation of the Image instance is: ", image.toString() ); console.log( "String representation of the Rectangle instance is: ", rect.toString() ); </script> </body> </html>

結論

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

更新於:2022年10月26日

273 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告