如何使用 FabricJS 將 Line 物件縮放至指定寬度?


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

語法

scaleToWidth(value: Number, absolute: Boolean): fabric.Object

引數

  • value − 此引數接受一個數字,用於確定線物件的新寬度值。

  • absolute − 此引數接受一個布林值,用於確定是否忽略視口。

Line 物件的預設外觀

示例

讓我們來看一個程式碼示例,以瞭解當不使用scaleToWidth方法時我們的線物件是什麼樣子。在這種情況下,我們的線物件不會在水平或垂直方向上縮放。

<!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 appearance of the Line object</h2> <p> You can see that the object has not been scaled in horizontal or vertical direction </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, }); // Add it to the canvas canvas.add(line); </script> </body> </html>

使用自定義值傳遞scaleToWidth方法

示例

在此示例中,我們將看到如何為scaleToWidth方法賦值,將我們的線物件縮放至指定寬度。由於我們已將值設定為 200,因此這將是我們的線物件的新寬度。

<!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>Passing the scaleToWidth method with a custom value</h2> <p> You can see that the new width of our line object is 200 </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, }); // Using the scaleToWidth method line.scaleToWidth(200, false); // Add it to the canvas canvas.add(line); </script> </body> </html>

更新於: 2022年10月25日

273 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.