如何使用 FabricJS 獲取文字的縮放寬度


在本教程中,我們將學習如何使用 FabricJS 獲取文字的縮放寬度。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供額外的功能,例如文字對齊、文字修飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。我們還可以使用 getScaledWidth 方法找到物件的縮放寬度。

語法

getScaledWidth()

示例 1

使用 getScaledWidth 方法

讓我們來看一個程式碼示例,看看使用 getScaledWidth 方法時的日誌輸出。在這種情況下,將返回物件的寬度。

<!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 getScaledWidth method</h2> <p>You can open console from dev tools and see that the width value is being displayed in the console</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 text object var text = new fabric.Text("Add sample
text here"
, { width: 300, fill: "green", fontWeight: "bold", }); // Add it to the canvas canvas.add(text); // Using getScaledWidth method console.log("The scaled width is", text.getScaledWidth()); </script> </body> </html>

示例 2

使用 getScaledWidth 方法並傳入 scaleX 屬性

讓我們來看一個程式碼示例,看看結合使用 getScaledWidth 方法和 scaleY 屬性時的日誌輸出。在這種情況下,最終的縮放寬度將顯示在控制檯中。

<!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 getScaledWidth method and passing the scaleX property</h2> <p>You can open console from dev tools and see that the width value is being displayed in the console has increased </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 text object var text = new fabric.Text("Add sample
text here"
, { width: 300, fill: "green", fontWeight: "bold", scaleX: 2, }); // Add it to the canvas canvas.add(text); // Using getScaledWidth method console.log("The scaled width is", text.getScaledWidth()); </script> </body> </html>

更新於: 2022年9月14日

746 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.