Function Text

A Text Game Object.

Text objects work by creating their own internal hidden Canvas and then renders text to it using the standard Canvas fillText API. It then creates a texture from this canvas which is rendered to your game during the render pass.

Because it uses the Canvas API you can take advantage of all the features this offers, such as applying gradient fills to the text, or strokes, shadows and more. You can also use custom fonts loaded externally, such as Google or TypeKit Web fonts.

Important: The font name must be quoted if it contains certain combinations of digits or special characters, either when creating the Text object, or when setting the font via setFont or setFontFamily, e.g.:

this.add.text(0, 0, 'Hello World', { fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif' });
this.add.text(0, 0, 'Hello World', { font: '"Press Start 2P"' });

You can only display fonts that are currently loaded and available to the browser: therefore fonts must be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, or have the fonts ready available in the CSS on the page in which your Phaser game resides.

See this compatibility table for the available default fonts across mobile browsers.

A note on performance: Every time the contents of a Text object changes, i.e. changing the text being displayed, or the style of the text, it needs to remake the Text canvas, and if on WebGL, re-upload the new texture to the GPU. This can be an expensive operation if used often, or with large quantities of Text objects in your game. If you run into performance issues you would be better off using Bitmap Text instead, as it benefits from batching and avoids expensive Canvas API calls.

Properties

contextTypes?: ValidationMap<any>

Lets you specify which legacy context is consumed by this component.

defaultProps?: Partial<GameObjectProps<Text>>

Used to define default values for the props accepted by the component.

type Props = { name?: string }

const MyComponent: FC<Props> = (props) => {
return <div>{props.name}</div>
}

MyComponent.defaultProps = {
name: 'John Doe'
}
displayName?: string

Used in debugging messages. You might want to set it explicitly if you want to display a different name for debugging purposes.


const MyComponent: FC = () => {
return <div>Hello!</div>
}

MyComponent.displayName = 'MyAwesomeComponent'
propTypes?: WeakValidationMap<GameObjectProps<Text>>

Used to declare the types of the props accepted by the component. These types will be checked during rendering and in development only.

We recommend using TypeScript instead of checking prop types at runtime.