javascript 在容器中居中文本 (EaselJS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19863135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center text in a container (EaselJS)
提问by Naor
I am new to EaselJS and I am trying to create a colored container with a centered text. This is my code:
我是 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();
For some reason the text doesn't centered in the container, but half of the text is out of the container. What is the problem in my code?
出于某种原因,文本没有在容器中居中,但有一半的文本在容器之外。我的代码有什么问题?
回答by Mister D.
Your text is horizontally centered around the x-position it was added (in your case x=0), that's why it is out of the container by half. If you want to center your text in your container, you'll have to define the position yourself :
您的文本以添加的 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);