FabricJS – 如何獲取當前例項所基於的影像元素?


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

語法

getElement(): HTMLImageElement 

使用getElement方法

示例

在這個例子中,我們使用了getElement方法來獲取當前例項所基於的影像元素。您可以從開發者工具中開啟控制檯以檢視返回的 HTML 影像元素。

<!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 getElement method</h2> <p>You can open the console from dev tools to see the logged output</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, skewX: 15, }); // Add it to the canvas canvas.add(image); // Using the getElement method console.log( "The image element on which the current instance is based on is as follows: ", image.getElement() ); </script> </body> </html>

getElement方法與fromURL方法一起使用

示例

讓我們看看當getElement方法與fromURL方法一起使用時記錄輸出的程式碼示例。在這裡,我們將能夠在控制檯中看到返回的影像元素。

<!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 getElement method along with fromURL method</h2> <p>You can open the console from dev tools to see the logged output</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Using fromURL method fabric.Image.fromURL( "https://tutorialspoint.tw/images/logo.png", function (Img) { canvas.add(Img); console.log( "The image element on which the current instance is based on is as follows: ", Img.getElement() ); } ); </script> </body> </html>

更新於: 2022年10月27日

679 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告