最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Center text in a container (EaselJS) - Stack Overflow

programmeradmin3浏览0评论

I am new to EaselJS and I am trying to create a colored container with a centered text. This is my code:

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?

I am new to EaselJS and I am trying to create a colored container with a centered text. This is my code:

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?

Share Improve this question edited Feb 18, 2015 at 15:04 gion_13 41.5k10 gold badges98 silver badges111 bronze badges asked Nov 8, 2013 at 15:50 NaorNaor 24.1k50 gold badges155 silver badges270 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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 :

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

评论列表(0)

  1. 暂无评论