在容器中居中文本(EaselJS)

7

我是EaselJS的新手,尝试创建带有居中文本的彩色容器。这是我的代码:

var width = 100, height = 100;
canvas.width = width + 10;
canvas.height = height + 10;
var container = new c.Container();
container.x = 10;
container.y = 10;
container.setBounds(0, 0, width, height);

var rect = new c.Shape();
rect.graphics.beginFill('#6e7e8e').drawRect(0, 0, width, height);
container.addChild(rect);

var text = new c.Text();
text.set({
    text: 'hello',
    textAlign: 'center'
});
container.addChild(text);
stage.addChild(container);
stage.update();

由于某些原因,文本没有居中在容器中,而是超出了一半。我的代码有什么问题?
1个回答

13

您的文本在水平方向上围绕添加时的x位置居中(在您的情况下为x = 0),这就是为什么它超出了容器一半的原因。如果您想在容器中心对齐文本,您需要自己定义位置:

text.set({
    text: 'hello',
});
var b = text.getBounds();
text.x = (width/2) - (b.width/2); 
text.y = (height/2) - (b.height/2);

3
你希望将文本放置在中心位置吗?可以使用 text.x = (width / 2) - (b.width / 2)。 - jjames
@Mister D.,如果文本采用“居中”或“右对齐”方式,如何更新其命中区域? - Abhishek Raj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接