如何使用 FabricJS 获取图像源?


在本教程中,我们将学习如何使用 FabricJS 获取图像源。我们可以通过创建fabric.Image的实例来创建图像对象。由于它是 FabricJS 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松对其进行自定义。为了查找图像的源,我们使用getSrc方法。

语法

getSrc(filtered: Boolean): String 

参数

  • filtered − 此参数是一个布尔值,指示是否需要svg的源。

使用getSrc方法

示例

在这个例子中,我们使用了getSrc方法来获取图像的原始源。在控制台中可以看到,返回的是图像源的字符串表示。

<!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 getSrc method</h2> <p> You can open the console from dev tools to see that the logged output contains the image source </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 getSrc method console.log("The Source of the image is: ", image.getSrc(false)); </script> </body> </html>

结合使用getSrc方法和fromURL方法

示例

让我们来看一下当getSrc方法与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 getSrc method along with fromURL method</h2> <p> You can open the console from dev tools to see that the logged output contains the image source </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); // Using getSrc method console.log("The Source of the image is: ", Img.getSrc(false)); } ); </script> </body> </html>

更新于: 2022年10月27日

浏览量:502

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.