在本教程中,我们将学习如何使用 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中文网其他相关文章!