0
# Text Rendering
1
2
Multiple text rendering approaches including canvas-based text, bitmap fonts, and HTML text for various performance and styling needs. PixiJS provides three distinct text rendering systems optimized for different use cases.
3
4
## Capabilities
5
6
### Canvas Text (Text Class)
7
8
Traditional canvas-based text rendering with full styling support.
9
10
```typescript { .api }
11
/**
12
* Canvas-based text rendering with full styling support
13
*/
14
class Text extends Sprite {
15
/** Text content */
16
text: string;
17
/** Text style */
18
style: TextStyle;
19
/** Canvas element used for text rendering */
20
canvas: HTMLCanvasElement;
21
/** Canvas 2D context */
22
context: CanvasRenderingContext2D;
23
/** Device pixel ratio */
24
resolution: number;
25
26
/**
27
* Create a new Text object
28
* @param text - Text content
29
* @param style - Text styling
30
* @param canvas - Optional canvas element
31
*/
32
constructor(text?: string, style?: Partial<ITextStyle>, canvas?: HTMLCanvasElement);
33
34
/** Get text width */
35
get width(): number;
36
set width(value: number);
37
38
/** Get text height */
39
get height(): number;
40
set height(value: number);
41
42
/**
43
* Update text rendering
44
* @param respectDirty - Only update if dirty
45
*/
46
updateText(respectDirty?: boolean): void;
47
48
/** Get text metrics */
49
getTextMetrics(): TextMetrics;
50
51
/** Destroy text object */
52
destroy(options?: boolean | IDestroyOptions): void;
53
}
54
```
55
56
### Text Style
57
58
Comprehensive styling options for canvas text.
59
60
```typescript { .api }
61
/**
62
* Text styling configuration
63
*/
64
class TextStyle {
65
/** Font family */
66
fontFamily: string | string[];
67
/** Font size */
68
fontSize: number | string;
69
/** Font style */
70
fontStyle: 'normal' | 'italic' | 'oblique';
71
/** Font variant */
72
fontVariant: string;
73
/** Font weight */
74
fontWeight: 'normal' | 'bold' | 'bolder' | 'lighter' | number | string;
75
/** Fill color(s) */
76
fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern;
77
/** Stroke color */
78
stroke: string | number;
79
/** Stroke thickness */
80
strokeThickness: number;
81
/** Text alignment */
82
align: 'left' | 'center' | 'right' | 'justify';
83
/** Baseline alignment */
84
textBaseline: 'alphabetic' | 'top' | 'hanging' | 'middle' | 'ideographic' | 'bottom';
85
/** Letter spacing */
86
letterSpacing: number;
87
/** Line height */
88
lineHeight: number;
89
/** Word wrapping */
90
wordWrap: boolean;
91
/** Word wrap width */
92
wordWrapWidth: number;
93
/** Break words */
94
breakWords: boolean;
95
/** Padding */
96
padding: number;
97
/** Trim whitespace */
98
trim: boolean;
99
/** Leading */
100
leading: number;
101
/** Drop shadow */
102
dropShadow: boolean;
103
/** Drop shadow alpha */
104
dropShadowAlpha: number;
105
/** Drop shadow angle */
106
dropShadowAngle: number;
107
/** Drop shadow blur */
108
dropShadowBlur: number;
109
/** Drop shadow color */
110
dropShadowColor: string | number;
111
/** Drop shadow distance */
112
dropShadowDistance: number;
113
/** Miter limit */
114
miterLimit: number;
115
/** Line cap */
116
lineCap: 'butt' | 'round' | 'square';
117
/** Line join */
118
lineJoin: 'miter' | 'round' | 'bevel';
119
/** Whitespace handling */
120
whiteSpace: 'normal' | 'pre' | 'pre-line';
121
122
/**
123
* Create a new TextStyle
124
* @param style - Style properties
125
*/
126
constructor(style?: Partial<ITextStyle>);
127
128
/** Clone text style */
129
clone(): TextStyle;
130
131
/** Reset to default style */
132
reset(): void;
133
134
/** Convert to font string */
135
toFontString(): string;
136
}
137
138
interface ITextStyle {
139
fontFamily?: string | string[];
140
fontSize?: number | string;
141
fontStyle?: 'normal' | 'italic' | 'oblique';
142
fontVariant?: string;
143
fontWeight?: 'normal' | 'bold' | 'bolder' | 'lighter' | number | string;
144
fill?: string | string[] | number | number[] | CanvasGradient | CanvasPattern;
145
stroke?: string | number;
146
strokeThickness?: number;
147
align?: 'left' | 'center' | 'right' | 'justify';
148
textBaseline?: 'alphabetic' | 'top' | 'hanging' | 'middle' | 'ideographic' | 'bottom';
149
letterSpacing?: number;
150
lineHeight?: number;
151
wordWrap?: boolean;
152
wordWrapWidth?: number;
153
breakWords?: boolean;
154
padding?: number;
155
trim?: boolean;
156
leading?: number;
157
dropShadow?: boolean;
158
dropShadowAlpha?: number;
159
dropShadowAngle?: number;
160
dropShadowBlur?: number;
161
dropShadowColor?: string | number;
162
dropShadowDistance?: number;
163
miterLimit?: number;
164
lineCap?: 'butt' | 'round' | 'square';
165
lineJoin?: 'miter' | 'round' | 'bevel';
166
whiteSpace?: 'normal' | 'pre' | 'pre-line';
167
}
168
```
169
170
### Text Metrics
171
172
Text measurement utilities for layout calculations.
173
174
```typescript { .api }
175
/**
176
* Text measurement utilities
177
*/
178
class TextMetrics {
179
/** Measured text */
180
text: string;
181
/** Text style */
182
style: TextStyle;
183
/** Text width */
184
width: number;
185
/** Text height */
186
height: number;
187
/** Line heights */
188
lines: string[];
189
/** Line widths */
190
lineWidths: number[];
191
/** Line height */
192
lineHeight: number;
193
/** Max line width */
194
maxLineWidth: number;
195
/** Font properties */
196
fontProperties: IFontMetrics;
197
198
/**
199
* Create text metrics
200
* @param text - Text to measure
201
* @param style - Text style
202
* @param width - Available width
203
* @param height - Available height
204
* @param lines - Text lines
205
* @param lineWidths - Line widths
206
* @param lineHeight - Line height
207
* @param maxLineWidth - Max line width
208
* @param fontProperties - Font properties
209
*/
210
constructor(text: string, style: TextStyle, width: number, height: number, lines: string[], lineWidths: number[], lineHeight: number, maxLineWidth: number, fontProperties: IFontMetrics);
211
212
/**
213
* Measure text with given style
214
* @param text - Text to measure
215
* @param style - Text style
216
* @param wordWrap - Enable word wrapping
217
* @param canvas - Optional canvas
218
*/
219
static measureText(text: string, style: TextStyle, wordWrap?: boolean, canvas?: HTMLCanvasElement): TextMetrics;
220
221
/**
222
* Measure font properties
223
* @param font - Font string
224
*/
225
static measureFont(font: string): IFontMetrics;
226
}
227
228
interface IFontMetrics {
229
ascent: number;
230
descent: number;
231
fontSize: number;
232
}
233
```
234
235
### Bitmap Text
236
237
High-performance bitmap font text rendering.
238
239
```typescript { .api }
240
/**
241
* High-performance bitmap font text rendering
242
*/
243
class BitmapText extends Container {
244
/** Text content */
245
text: string;
246
/** Font name */
247
fontName: string;
248
/** Font size */
249
fontSize: number;
250
/** Text tint */
251
tint: number;
252
/** Text alignment */
253
align: 'left' | 'center' | 'right';
254
/** Anchor point */
255
anchor: ObservablePoint;
256
/** Letter spacing */
257
letterSpacing: number;
258
/** Max width */
259
maxWidth: number;
260
/** Max height */
261
maxHeight: number;
262
263
/**
264
* Create bitmap text
265
* @param text - Text content
266
* @param style - Bitmap text style
267
*/
268
constructor(text: string, style?: Partial<IBitmapTextStyle>);
269
270
/** Get text width */
271
get textWidth(): number;
272
273
/** Get text height */
274
get textHeight(): number;
275
276
/** Update text rendering */
277
updateText(): void;
278
279
/** Validate text */
280
validate(): void;
281
282
/** Get bounds */
283
getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle;
284
285
/** Destroy bitmap text */
286
destroy(options?: boolean | IDestroyOptions): void;
287
}
288
289
interface IBitmapTextStyle {
290
fontName?: string;
291
fontSize?: number;
292
tint?: number;
293
align?: 'left' | 'center' | 'right';
294
letterSpacing?: number;
295
maxWidth?: number;
296
}
297
```
298
299
### Bitmap Font Management
300
301
System for loading and managing bitmap fonts.
302
303
```typescript { .api }
304
/**
305
* Bitmap font management system
306
*/
307
class BitmapFont {
308
/** Font information */
309
font: IBitmapFontData;
310
/** Page textures */
311
pageTextures: Record<string, Texture>;
312
/** Font size */
313
size: number;
314
/** Distance field */
315
distanceField: IBitmapFontDistanceField;
316
317
/**
318
* Create bitmap font from options
319
* @param data - Font data
320
* @param textures - Page textures
321
* @param ownsTextures - Whether font owns textures
322
*/
323
constructor(data: IBitmapFontData, textures: Record<string, Texture>, ownsTextures?: boolean);
324
325
/**
326
* Create bitmap font from configuration
327
* @param name - Font name
328
* @param textStyle - Text style
329
* @param options - Font options
330
*/
331
static from(name: string, textStyle?: TextStyle | Partial<ITextStyle>, options?: IBitmapFontOptions): BitmapFont;
332
333
/**
334
* Install bitmap font
335
* @param data - Font data or URL
336
* @param textures - Textures or texture URLs
337
* @param ownsTextures - Whether to own textures
338
*/
339
static install(data: string | IBitmapFontData | BitmapFontData, textures?: Texture | Texture[] | Record<string, Texture>, ownsTextures?: boolean): BitmapFont;
340
341
/**
342
* Uninstall bitmap font
343
* @param name - Font name
344
*/
345
static uninstall(name: string): void;
346
347
/**
348
* Get available fonts
349
*/
350
static getAvailable(): Record<string, BitmapFont>;
351
352
/** Destroy bitmap font */
353
destroy(): void;
354
}
355
356
interface IBitmapFontData {
357
info: IBitmapFontDataInfo[];
358
common: IBitmapFontDataCommon[];
359
page: IBitmapFontDataPage[];
360
char: IBitmapFontDataChar[];
361
kerning: IBitmapFontDataKerning[];
362
distanceField: IBitmapFontDataDistanceField[];
363
}
364
365
interface IBitmapFontOptions {
366
chars?: string | (string | string[])[];
367
resolution?: number;
368
textureWidth?: number;
369
textureHeight?: number;
370
padding?: number;
371
}
372
```
373
374
### HTML Text
375
376
HTML/CSS-based text rendering for rich formatting.
377
378
```typescript { .api }
379
/**
380
* HTML/CSS-based text rendering for rich text formatting
381
*/
382
class HTMLText extends Sprite {
383
/** HTML text content */
384
text: string;
385
/** HTML text style */
386
style: HTMLTextStyle;
387
/** Local style ID */
388
localStyleID: number;
389
390
/**
391
* Create HTML text
392
* @param text - HTML text content
393
* @param style - HTML text style
394
*/
395
constructor(text?: string, style?: Partial<IHTMLTextStyle>);
396
397
/** Update text */
398
updateText(): void;
399
400
/** Get text metrics */
401
getTextMetrics(): TextMetrics;
402
403
/** Destroy HTML text */
404
destroy(options?: boolean | IDestroyOptions): void;
405
}
406
407
/**
408
* HTML text styling
409
*/
410
class HTMLTextStyle extends TextStyle {
411
/** HTML tags styles */
412
tagStyles: Record<string, Partial<ITextStyle>>;
413
414
constructor(style?: Partial<IHTMLTextStyle>);
415
416
/** Clone HTML text style */
417
clone(): HTMLTextStyle;
418
}
419
420
interface IHTMLTextStyle extends ITextStyle {
421
tagStyles?: Record<string, Partial<ITextStyle>>;
422
}
423
```
424
425
**Usage Examples:**
426
427
```typescript
428
import { Text, BitmapText, HTMLText, TextStyle, BitmapFont } from "pixi.js";
429
430
// Canvas text with custom styling
431
const style = new TextStyle({
432
fontFamily: 'Arial',
433
fontSize: 36,
434
fontStyle: 'italic',
435
fontWeight: 'bold',
436
fill: ['#ffffff', '#00ff99'], // Gradient
437
stroke: '#4a1850',
438
strokeThickness: 5,
439
dropShadow: true,
440
dropShadowColor: '#000000',
441
dropShadowBlur: 4,
442
dropShadowAngle: Math.PI / 6,
443
dropShadowDistance: 6,
444
wordWrap: true,
445
wordWrapWidth: 440,
446
lineJoin: 'round',
447
});
448
449
const text = new Text('This is a PixiJS text', style);
450
app.stage.addChild(text);
451
452
// Bitmap text for performance
453
BitmapFont.from('TitleFont', {
454
fontFamily: 'Arial',
455
fontSize: 48,
456
fill: 'white',
457
stroke: 'black',
458
strokeThickness: 2
459
});
460
461
const bitmapText = new BitmapText('High Performance Text', {
462
fontName: 'TitleFont',
463
fontSize: 48,
464
align: 'center'
465
});
466
467
// HTML text for rich formatting
468
const htmlText = new HTMLText('Hello <b>World</b>!', {
469
fontFamily: 'Arial',
470
fontSize: 24,
471
fill: 0x000000,
472
tagStyles: {
473
b: { fontWeight: 'bold', fill: 0xff0000 },
474
i: { fontStyle: 'italic' },
475
code: { fontFamily: 'monospace', fill: 0x333333 }
476
}
477
});
478
479
// Text measurement
480
const metrics = TextMetrics.measureText('Sample text', style);
481
console.log(`Text dimensions: ${metrics.width} x ${metrics.height}`);
482
483
// Multiline text
484
const multilineText = new Text('Line 1\nLine 2\nLine 3', {
485
fontSize: 24,
486
fill: 0xffffff,
487
align: 'center',
488
lineHeight: 30
489
});
490
491
// Dynamic text updates (requires TickerPlugin)
492
let counter = 0;
493
// app.ticker.add(() => {
494
// text.text = `Frame: ${counter++}`;
495
// });
496
```
497
498
## Text Rendering Performance
499
500
**Canvas Text (Text):**
501
- Best for: Rich styling, effects, gradients
502
- Performance: Moderate (canvas-based)
503
- Features: Full CSS-like styling
504
505
**Bitmap Text (BitmapText):**
506
- Best for: High-performance, large amounts of text
507
- Performance: Excellent (texture-based)
508
- Features: Limited styling, requires pre-generated fonts
509
510
**HTML Text (HTMLText):**
511
- Best for: Rich HTML formatting, mixed styles
512
- Performance: Good (texture-based)
513
- Features: HTML tags, CSS-like styling
514
515
```typescript
516
// Performance comparison example
517
// Slow: Many individual Text objects
518
for (let i = 0; i < 100; i++) {
519
const text = new Text(`Item ${i}`, style);
520
text.position.set(10, i * 25);
521
container.addChild(text);
522
}
523
524
// Fast: Single BitmapText per item
525
BitmapFont.from('ListFont', { fontFamily: 'Arial', fontSize: 18 });
526
for (let i = 0; i < 100; i++) {
527
const text = new BitmapText(`Item ${i}`, { fontName: 'ListFont' });
528
text.position.set(10, i * 25);
529
container.addChild(text);
530
}
531
532
// Even faster: Single Text object with all content
533
const allItems = Array.from({ length: 100 }, (_, i) => `Item ${i}`).join('\n');
534
const singleText = new Text(allItems, style);
535
container.addChild(singleText);
536
```