在本教程中,我们将学习如何使用 FabricJS 更改 Line 对象的 URL 字符串的格式。Line 元素是 FabricJS 中提供的基本元素之一。它用于创建直线。因为线元素在几何上是一维的并且不包含内部,所以它们永远不会被填充。我们可以通过创建 fabric.Line 的实例来创建线条对象,指定线条的 x 和 y 坐标并将其添加到画布中。为了改变 Line 对象的 URL 字符串的格式,我们使用格式属性。
toDataURL({ format: String }: Object): String
选项(可选)- 此参数是一个对象,它为 Line 对象的 URL 表示提供额外的自定义。使用此参数高度、质量、乘数和许多其他属性都可以更改,其中格式是一个属性。
format - 此属性接受一个String值,它允许我们定义输出图像的格式。可接受的值为“jpeg”或“png”。默认值为“png”。
让我们看一个代码示例,以查看在不使用格式属性的情况下使用 toDataURL 方法时记录的输出。一旦我们从开发工具打开控制台,我们就可以看到 Line 对象的 URL 表示。我们可以复制该 URL 并将其粘贴到新选项卡的地址栏中以查看最终输出。由于我们没有指定图像的格式,它将根据设置的默认值“png”。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Default value without using the format property</h2> <p> You can open console from dev tools and see that the URL representation of the Line object has a "png" format by default </p> <canvas id="canvas"></canvas> <script> //启动画布实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); //启动一个 Line 对象 var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, angle: 70, }); //将其添加到画布 canvas.add(line); //使用 toDataURL 方法 console.log(line.toDataURL()); </script> </body> </html>
让我们看一个代码示例,看看当toDataURL方法与 format 属性一起使用时 Line 对象的样子。在这种情况下,我们将能够指定最终图像的格式。由于此处分配的值为“jpeg”,因此最终图像将采用“jpeg”格式。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Using the toDataURL method along with format property</h2> <p> You can open console from dev tools and see that the URL representation of the Line object has a "jpeg" format now </p> <canvas id="canvas"></canvas> <script> //启动画布实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); //启动一个 Line 对象 var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, angle: 70, }); //将其添加到画布 canvas.add(line); //使用 toDataURL 方法 console.log(line.toDataURL({format: "jpeg"})); </script> </body> </html>