Sign in to follow this  
xetra11

How to center a text within a container?

Recommended Posts

Hey guys,

Please take a look at this JSFiddle: https://jsfiddle.net/r4yfozsw/1/

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.

https://jsfiddle.net/08pd502z/

HTH

vitalije

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:

buttonText.x=475;
buttonText.y=350;
buttonText.anchor.set(0.5);

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.