FabricJS – 如何获取当前实例所基于的图像元素?
fabricjsjavascripthtml5 canvas
在本教程中,我们将学习如何使用 FabricJS 获取当前实例所基于的图像元素。我们可以通过创建 fabric.Image 实例来创建 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://www.tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // 启动一个canvas实例 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, }); // 将其添加到画布 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> // 启动一个canvas实例 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>