FabricJS – 如何在 Line 物件的 URL 字串中設定縮放倍數?


在本教程中,我們將學習如何使用 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> // Initiate a canvas instance 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, }); // Add it to the canvas 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> // Initiate a canvas instance 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, }); // Add it to the canvas canvas.add(line); // Using the toDataURL method console.log(line.toDataURL({ multiplier: 2 })); </script> </body> </html>

更新於: 2022年10月25日

313 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.