如何使用 FabricJS 将文本对象水平和垂直居中于画布上?


在本教程中,我们将学习如何使用 FabricJS 将文本对象水平和垂直居中于画布上。我们可以通过添加 fabric.Text 的实例来在画布上显示文本。它不仅允许我们移动、缩放和更改文本的尺寸,还提供其他功能,例如文本对齐、文本修饰、行高,这些功能可以通过 textAlign、underline 和 lineHeight 属性分别获得。我们还可以使用 center 方法将文本对象水平和垂直居中于画布上。

语法

center()

示例 1

文本对象的默认外观

让我们看一个代码示例,了解当不使用 center 方法时我们的文本对象是什么样子。在这种情况下,文本对象不会居中于画布上。

<!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 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", textAlign: "center", }); // Add it to the canvas canvas.add(text); </script> </body> </html>

示例 2

使用 center 方法

在本例中,我们将看到如何通过使用 center 方法,能够将文本对象精确放置在画布的中心。在这种情况下,对象水平和垂直居中。

<!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 center method</h2> <p>You can see that the text object has been centered 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", textAlign: "center", }); // Add it to the canvas canvas.add(text); // Using center() to center the text object on the canvas text.center(); </script> </body> </html>

更新于: 2022-09-13

310 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.