pixijs H5游戏开发入门(二)文本对象在画布中居中显示

本系列文章

本文编写时 pixijs 版本: v7.3.2

思考一个问题,文本对象(Text)如何在画布上居中显示?

前一篇文章中,文本对象(Text)显示在了黑色画布的左上角。

官方文档

Text对象的官方文档:https://pixijs.download/v7.3.2/docs/PIXI.Text.html

其中的 anchor 属性官方文档是这么说的:

The anchor sets the origin point of the sprite. The default value is taken from the Texture and passed to the constructor.

The default is (0,0), this means the sprite’s origin is the top left.

Setting the anchor to (0.5,0.5) means the sprite’s origin is centered.

Setting the anchor to (1,1) would mean the sprite’s origin point will be the bottom right corner.

默认值为(0,0),这意味着精灵的原点在左上角。
将锚点设置为(0.5,0.5)意味着精灵的原点居中。
将锚点设置为(1,1)意味着精灵的原点将位于右下角。


还有 xy 这两个坐标属性:

x number
The position of the displayObject on the x axis relative to the local coordinates of the parent. An alias to position.x

y number
The position of the displayObject on the y axis relative to the local coordinates of the parent. An alias to position.y

意思是 xy 可以设置显示元素相对于父元素的坐标位置。

试一下

nginx html 目录新增 example-02.html,在 example-01.html 的基础上设置 message 的 anchor 和坐标,可以使用 http://localhost/pixi/example-02.html 进行查看效果。

xy 设置为画布的一半,让渲染位置为画布中央,再将 anchor 设置为 0.5,让锚点位置设置为原点居中。

代码片段
1
2
3
4
5
6
7
8
9
10
let message = new Text("Hello World", style);
// message.anchor.set(0.5);
// 或者
message.anchor.set(0.5, 0.5);
// 或者
// message.anchor.x = 0.5;
// message.anchor.y = 0.5;
// 设置message坐标
message.x = app.renderer.width / 2;
message.y = app.renderer.height / 2;

看看效果:

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>入门示例02</title>
<script src="./js/pixi.js"></script>
<style>
* {margin:0;padding:0}
</style>
</head>
<body>
<script>
const {Application, TextStyle, Text} = PIXI
// 创建一个 pixi 实例
let app = new Application({
width: 256,
height: 256
});
let style = new TextStyle({
fontFamily: "Futura",
fontSize: 24,
fill: "white"
});
let message = new Text("Hello World", style);
// message.anchor.set(0.5);
// 或者
message.anchor.set(0.5, 0.5);
// 或者
// message.anchor.x = 0.5;
// message.anchor.y = 0.5;
// 设置message坐标
message.x = app.renderer.width / 2;
message.y = app.renderer.height / 2;
app.stage.addChild(message);

// 插入到 body 中
document.body.appendChild(app.view);
</script>
</body>
</html>

如上所示,文本居中显示效果完美实现,基于此原理,也可以实现按钮文本居中效果。

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2023-11-22/js-pixi-text-center/

如果您觉得文章不错,可以点击文章中的广告支持一下!