容器中的中心文本(EaselJS)

时间:2013-11-08 15:50:10

标签: javascript canvas easeljs createjs

我是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 个答案:

答案 0 :(得分:11)

你的文字水平居中于它添加的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);