FabricJS – 如何更改 Line 物件的 URL 字串格式?


在本教程中,我們將學習如何使用 FabricJS 更改 Line 物件的 URL 字串格式。Line 元素是 FabricJS 提供的基本元素之一。它用於建立直線。由於線元素在幾何上是一維的,並且不包含內部,因此它們永遠不會填充。我們可以透過建立 fabric.Line 的例項,指定線的 x 和 y 座標並將其新增到畫布上來建立線物件。為了更改 Line 物件的 URL 字串格式,我們使用 format 屬性。

語法

toDataURL({ format: String }: Object): String

引數

  • options(可選) - 此引數是一個物件,它為 Line 物件的 URL 表示提供額外的自定義。使用此引數,可以更改高度、質量、乘數以及許多其他屬性,其中format 是一個屬性。

選項鍵

  • format - 此屬性接受一個字串值,允許我們定義輸出影像的格式。接受的值為“jpeg”或“png”。預設值為“png”。

不使用format 屬性時的預設值

示例

讓我們看一個程式碼示例,以檢視在不使用format 屬性的情況下使用 toDataURL 方法時記錄的輸出。一旦我們從開發者工具中開啟控制檯,我們就可以看到 Line 物件的 URL 表示。我們可以複製該 URL 並將其貼上到新標籤頁的位址列中以檢視最終輸出。由於我們沒有指定影像的格式,因此它將根據設定的預設值“png”進行顯示。

<!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>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> // 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>

使用toDataURL 方法以及 format 屬性

示例

讓我們看一個程式碼示例,以檢視在toDataURL 方法與 format 屬性一起使用時 Line 物件的外觀。在這種情況下,我們將能夠指定最終影像的格式。由於這裡分配的值為“jpeg”,因此最終影像將為“jpeg”格式。

<!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 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> // 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({format: "jpeg"})); </script> </body> </html>

更新於: 2022年10月20日

163 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.