0
\$\begingroup\$

I am just starting to learn the Phaser JS framework with my first game. I did not managed to find a way how i can align text inside a rectangle element dynamically without specific coordinates. Here is what i have

pointH11L1 = game.add.text(0, 0, '20'); 
pointH11L1.stroke = "#000";
pointH11L1.strokeThickness = 4;
pointH11L1.font = 'oswaldbold';
pointH11L1.fontSize = 22;
pointH11L1.fill = '#999999';
//pointH11L1.alignIn(graphicsRectH12L2, Phaser.CENTER);
graphicsRectH12L2.addChild(pointH11L1);
pointH11L1.x = pointH11L1.width / 2 - 6; 
pointH11L1.y = -2.5;

//graphicsRectH12L2 is the rectangle inside which i need to align.

var graphicsRectH12L2 = this.game.add.graphics(950, 405); 
    graphicsRectH12L2.beginFill(0xffcd00, 1);
    graphicsRectH12L2.drawRect(0, 0, 44, 29);
    graphicsRectH12L2.endFill(0xffcd00, 1);
    group.add(graphicsRectH12L2);
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I extended the Phaser.Graphics and added a Phaser.Text inside it, and center the text inside the graphics, like so:

var textStyle = {
    font: "normal 24px Arial",
    fill: '#ffffff',
    align: 'center',
    boundsAlignH: "center", // bounds center align horizontally
    boundsAlignV: "middle" // bounds center align vertically
};
var textElement = new Phaser.Text(game, 0, 0, "Hello World", textStyle);
var graphics = new Phaser.Graphics(game, 0, 0);

// graphics and textElement bounds/sizes must be the same
// so your text area covers the whole rectangle
graphics.drawRect(0, 0, 400, 100);
textElement.setTextBounds(0, 0, 400, 100);

graphics.addChild(textElement);
game.world.addChild(graphics);

// That's it! Now the text should be centered horizontally and vertically
// in the graphics element
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.