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.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方法一起使用
示例
让我们看看当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.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>
广告