FabricJS – 如何在 Line 对象的 URL 字符串中设置缩放倍数?

fabricjsjavascripthtml5 canvas

在本教程中,我们将学习如何使用 FabricJS 在 Line 对象的 URL 字符串中设置缩放倍数。Line 元素是 FabricJS 中提供的基本元素之一。它用于创建直线。由于线元素在几何上是一维的并且不包含内部,因此它们永远不会被填充。我们可以通过创建 fabric.Line 实例、指定线的 x 和 y 坐标并将其添加到画布来创建线对象。为了在 Line 对象的 URL 字符串中设置缩放乘数,我们使用 multiplier 属性。

语法

toDataURL({ multiplier: Number }: Object): String

参数

  • options(可选)− 此参数是一个 Object,它为 Line 对象的 URL 表示提供额外的自定义。使用此参数可以更改高度、质量、格式和许多其他属性,其中 multiplier 是一个属性。

选项键

  • multiplier − 此属性接受 Number 值,表示缩放最终 Line 输出图像的乘数。默认值为 1。

不使用 multiplier 属性

示例

让我们看一个代码示例,以查看未使用 multiplier 属性时的输出图像。一旦我们从开发工具打开控制台,我们就可以看到 Line 对象的 URL 表示。我们可以复制该 URL 并将其粘贴到新选项卡的地址栏中以查看最终输出。由于我们没有使用 multiplier 属性,因此将使用默认乘数值,即 1。

<!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>Without using the multiplier property</h2> <p> You can open console from dev tools and see the output URL. You can copy that and paste it in the address bar of a new tab to see the image. </p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, angle: 70, }); // 将其添加到画布 canvas.add(line); // Using the toDataURL method console.log(line.toDataURL()); </script> </body> </html>

使用 multiplier 属性

示例

让我们看一个代码示例,看看当使用 multiplier 属性时 Line 对象的最终输出图像是什么样子。在本例中,我们给它传递了一个值 2。因此,最终图像将在 x 和 y 方向上缩放两倍。

<!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 multiplier property</h2> <p> You can open console from dev tools and see the output URL. You can copy that and paste it in the address bar of a new tab to see the image. </p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, angle: 70, }); // 将其添加到画布 canvas.add(line); // Using the toDataURL method console.log(line.toDataURL({ multiplier: 2 })); </script> </body> </html>

相关文章