如何使用 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>

更新于: 2022-09-13

865 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.