如何使用 FabricJS 使文字物件在水平和垂直方向上等比例縮放?
在本教程中,我們將學習如何使用 FabricJS 使文字物件在水平和垂直方向上等比例縮放。我們可以透過新增 fabric.Text 的例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字裝飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。類似地,我們也可以使用 scale 方法縮放文字物件。
語法
scale(value: Number)
引數
scale − 此引數接受一個數字,用於設定文字物件的縮放因子。
示例 1
文字物件的預設外觀
讓我們看一個程式碼示例,瞭解在不使用 scale 方法時文字物件的外觀。在這種情況下,我們的文字物件不會在水平和垂直方向上縮放。
<!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 Text 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 text object var text = new fabric.Text("Add sample
text here.", { width: 300, left: 60, top: 70, fill: "green", }); // Add it to the canvas canvas.add(text); </script> </body> </html>
示例 2
使用自定義值傳遞 scale 方法
在本例中,我們將看到如何為 scale 方法賦值,使我們的文字物件在水平和垂直方向上等比例縮放。由於我們傳遞的值為 2,因此現在將考慮該縮放因子。
<!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 scale method with a custom value</h2> <p>You can see that the object has been scaled equally in horizontal and 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 text object var text = new fabric.Text("Add sample
text here.", { width: 300, left: 110, top: 70, fill: "green", }); // Using the scale method text.scale(2); // Add it to the canvas canvas.add(text); </script> </body> </html>
廣告