如何使用 FabricJS 將文字物件水平居中於畫布上?
在本教程中,我們將學習如何使用 FabricJS 將文字物件水平居中於畫布上。我們可以透過新增 fabric.Text 的例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字裝飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。我們還可以使用 centerH 方法將文字物件水平居中於畫布上。
語法
centerH()
示例 1
文字物件的預設外觀
讓我們看一個程式碼示例,瞭解當不使用 centerH 方法時文字物件的外觀。在這種情況下,文字物件不會水平居中於畫布上。
<!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 text object has not been centered horizontally on the canvas</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); </script> </body> </html>
示例 2
使用 centerH 方法
在本示例中,我們將看到如何透過使用 centerH 方法,能夠將文字物件精確地放置在畫布的水平中心。在這種情況下,物件水平居中。
<!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 centerH method</h2> <p>You can see that the text object has now been centered horizontally on the canvas</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 the centerH() method to center text object horizontally text.centerH(); </script> </body> </html>
廣告