Displaying text

Use a Text object (PIXI.Text) to display text on the stage. In its simplest form, you can do it like this:

  1. let message = new Text("Hello Pixi!");
  2. 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:

  1. message.position.set(54, 96);

Displaying text

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:

  1. let style = new TextStyle({
  2. fontFamily: "Arial",
  3. fontSize: 36,
  4. fill: "white",
  5. stroke: '#ff3300',
  6. strokeThickness: 4,
  7. dropShadow: true,
  8. dropShadowColor: "#000000",
  9. dropShadowBlur: 4,
  10. dropShadowAngle: Math.PI / 6,
  11. dropShadowDistance: 6,
  12. });

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:

  1. let message = new Text("Hello Pixi!", style);

Displaying text

If you want to change the content of a text object after you’ve created it, use the text property.

  1. message.text = "Text changed!";

Use the style property if you want to redefine the style properties.

  1. 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.

  1. 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.

  1. @font-face {
  2. font-family: "fontFamilyName";
  3. src: url("fonts/fontFile.ttf");
  4. }

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.