如何使用FabricJS设置文本转换的垂直原点?

在本教程中,我们将学习如何使用 FabricJS 设置文本转换的垂直原点。我们可以通过添加 Fabric.Text 的实例在画布上显示文本。它不仅允许我们移动、缩放和更改文本的尺寸,而且还提供了附加功能,例如文本对齐、文本装饰、行高,这些功能可以分别通过属性 textAlign、underline 和 lineHeight 获得。同样,我们也可以使用originY属性设置变换的垂直原点。
语法
new fabric.Text(text: String , { originY : String }: Object)
参数
text - 此参数接受 String,这是我们要显示的文本字符串。
选项(可选) - 此参数是一个对象,它为我们的文本提供额外的自定义。使用此参数,可以更改与 originY 为属性的对象相关的颜色、光标、边框宽度和许多其他属性。
选项键
originY - 该属性接受一个String值,它允许我们设置转换的垂直原点。可能的值为“顶部”、“底部”和“中心”。它的默认值为“top”。
示例 1
文本对象的默认外观
让我们看一个代码示例,看看不使用 originY 属性时文本对象的外观。在这种情况下,变换的垂直原点将为顶部,这也是默认值。
<!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 vertical origin of transformation is towards top</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: 50,
top: 70,
fill: "green",
});
// Add it to the canvas
canvas.add(text);
</script>
</body>
</html>
示例 2
将 originY 属性作为键传递给值
在此示例中,我们将看到为 originY 属性分配值如何更改变换的垂直原点。我们在本例中使用了两个文本对象来显示差异。在我们的第一个文本对象中,由于我们将值传递为“bottom”,所以变换的垂直原点现在位于底部。相同的顶部属性 100 应用于两个文本,但由于转换的垂直原点发生变化,它们仍然处于不同的垂直位置。
<!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 originY property as key with a value</h2>
<p>You can see that origin of transformation for the first text object(text1) is bottom while text2 maintains the default vertical origin of transformation</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 text1 = new fabric.Text("Text 1", {
width: 300,
left: 200,
top: 100,
fill: "green",
originY: "bottom",
});
// Initiate a text object
var text2 = new fabric.Text("Text 2", {
width: 300,
left: 50,
top: 100,
fill: "red",
});
// Add it to the canvas
canvas.add(text1);
canvas.add(text2);
</script>
</body>
</html>
javascript