如何使用 FabricJS 將文字物件垂直居中在畫布上?
在本教程中,我們將學習如何使用 FabricJS 將文字物件垂直居中在畫布上。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供額外的功能,例如文字對齊、文字修飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。我們還可以使用 centerV 方法將文字物件垂直居中在畫布上。
語法
centerV()
示例 1
文字物件的預設外觀
讓我們來看一個程式碼示例,看看在不使用 centerV 方法時文字物件的外觀。在這種情況下,文字物件不會垂直居中在畫布上。
<!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 vertically 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
使用 centerV 方法
在這個例子中,我們將看到如何透過使用 centerV 方法,將文字物件精確地放置在畫布的垂直中心。在這種情況下,物件垂直居中。
<!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 centerV method</h2> <p>You can see that the text object has now been centered vertically 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 centerV() method to center text object vertically text.centerV(); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP