在本教程中,我們將學習如何使用 FabricJS 來取得目前實例所基於的映像元素。我們可以透過建立fabric.Image的實例來建立一個Image物件。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆自訂它。為了取得目前實例所基於的圖像元素,我們使用 getElement 方法。
getElement(): HTMLImageElement
在這個例子中,我們使用了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://www.tutorialspoint.com/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 方法結合使用時記錄的輸出的程式碼範例。在這裡,我們將能夠看到控制台中返回的圖像元素。
<!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://www.tutorialspoint.com/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>
以上是FabricJS – 如何取得目前實例所基於的影像元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!