Sign in to follow this  

How to center a text within a container?

Recommended Posts

Hey guys,

Please take a look at this JSFiddle:

As you can see I'm trying to have a button with a text on it. Therefore I create a Graphics object and draw it as a Rectangle. Afterwards I add a Text object to its children AND this Text object receives an option called "align : center". That way I expected the Text to be centered to its local container.

Sadly the Text just got rendered at the global x:0;y:0 :(

Can somebody tell me what I'm misunderstanding in regards to the container system of PIXI.js?


greets Charlie!

Share this post

Link to post
Share on other sites

You need to set anchor on text sprite to be (0.5, 0.5) in order to place the center of text on given position.

You have also created rectangle that is already offset to 400, 300. It is better to draw rectangle at (0, 0), and then change its position to (400, 300)

Finally, the center of rectangle is at (75, 50) because its width is 150 and height 100. That means text should be positioned on 75, 50.



Share this post

Link to post
Share on other sites

Set the anchor point on the x axis of the text to 0.5 for it to be centred. remember, the text gets converted to and drawn as a sprite, so by default if that sprite got bigger, it would extend from the top left. 

The align property is useful when you have text over multiple lines; then you'll see it work more as you'd expect

Share this post

Link to post
Share on other sites
7 minutes ago, o0Corps0o said:


or you could add them to a group? and then move the group accordingly?

But these position coordinates are still global?

I thought about something like

buttonText.local.x = 0
buttonText.local.y = 0

And then I expect the Text to be at the left top corner of the Rectangle Shape. That's what I actually want to achieve. So when moving the Button Rectangle the Text always goes with it.

Thanks for you attention btw!

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.