Displaying text
Use a Text
object (PIXI.Text
) to display text on the stage. In its simplest form, you can do it like this:
let message = new Text("Hello Pixi!");
app.stage.addChild(message);
This will display the words, “Hello, Pixi” on the canvas. Pixi’s Text objects inherit from the Sprite
class, so they contain all the same properties like x
, y
, width
, height
, alpha
, and rotation
. Position and resize text on the stage just like you would any other sprite. For example, you could use position.set
to set the message
‘s x
and y
position like this:
message.position.set(54, 96);
That will give you basic, unstyled text. But if you want to get fancier, use Pixi’s TextStyle
function to define custom text styling. Here’s how:
let style = new TextStyle({
fontFamily: "Arial",
fontSize: 36,
fill: "white",
stroke: '#ff3300',
strokeThickness: 4,
dropShadow: true,
dropShadowColor: "#000000",
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 6,
});
That creates a new style
object containing all the text styling that you’d like to use. For a complete list of all the style properties you can use, see here.
To apply the style to the text, add the style
object as the Text
function’s second argument, like this:
let message = new Text("Hello Pixi!", style);
If you want to change the content of a text object after you’ve created it, use the text
property.
message.text = "Text changed!";
Use the style
property if you want to redefine the style properties.
message.style = {fill: "black", font: "16px PetMe64"};
Pixi makes text objects by using the Canvas Drawing API to render the text to an invisible and temporary canvas element. It then turns the canvas into a WebGL texture so that it can be mapped onto a sprite. That’s why the text’s color needs to be wrapped in a string: it’s a Canvas Drawing API color value. As with any canvas color values, you can use words for common colors like “red” or “green”, or use rgba, hsla or hex values.
Pixi can also wrap long lines of text. Set the text’s wordWrap
style property to true
, and then set wordWrapWidth
to the maximum length in pixels, that the line of text should be. Use the align
property to set the alignment for multi-line text.
message.style = {wordWrap: true, wordWrapWidth: 100, align: center};
(Note: align
doesn’t affect single line text.)
If you want to use a custom font file, use the CSS @font-face
rule to link the font file to the HTML page where your Pixi application is running.
@font-face {
font-family: "fontFamilyName";
src: url("fonts/fontFile.ttf");
}
Add this @font-face
rule to your HTML page’s CSS style sheet.
Pixi also has support for bitmap fonts. You can use Pixi’s loader to load Bitmap font XML files, the same way you load JSON or image files.