如何在 FabricJS 中設定文字例項的旋轉角度?


在本教程中,我們將學習如何使用 FabricJS 設定文字例項的旋轉角度。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字裝飾、行高,這些功能分別可以透過 textAlign、underline 和 lineHeight 屬性獲得。同樣,我們也可以使用 rotate 方法設定例項的旋轉角度。

語法

rotate(angle: Number)

引數

  • angle − 此引數接受一個數字,該數字設定例項以中心旋轉的角度

示例 1

文字物件的預設外觀

讓我們來看一個程式碼示例,看看在不使用 rotate 方法時文字物件是什麼樣的。在這種情況下,我們的文字物件不會旋轉任何角度。

<!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 angle of rotation of text object is zero</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

使用自定義值傳遞 rotate 方法

在這個例子中,我們將看到如何為 rotate 方法賦值會使我們的文字物件旋轉一定的角度。由於我們傳入的值為 45,因此例項將旋轉 45 度。

<!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 rotate method with a custom value</h2> <p>You can see that the angle of rotation of text object is 45 degrees</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 rotate method text.rotate(45); // Add it to the canvas canvas.add(text); </script> </body> </html>

更新於:2022年9月14日

170 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告