or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

animation-interaction.mdapplication.mdassets.mddisplay-objects.mdgraphics-rendering.mdindex.mdtext.md

text.mddocs/

0

# Text Rendering

1

2

PIXI.js provides three distinct text rendering engines, each optimized for different use cases and performance requirements. Understanding the strengths and limitations of each engine helps developers choose the right approach for their specific needs.

3

4

## Text Rendering Engines Overview

5

6

PIXI.js offers three text rendering approaches:

7

8

- **Text (Canvas-based)** - Full-featured text rendering using HTML5 Canvas API with complete styling support and real-time updates

9

- **BitmapText (Performance-optimized)** - Ultra-fast text rendering using pre-generated bitmap fonts, ideal for performance-critical applications

10

- **HTMLText (CSS-based)** - Rich HTML/CSS text rendering with advanced formatting capabilities, perfect for complex layouts and web-like text styling

11

12

### When to Use Each Engine

13

14

**Use Text when:**

15

- You need full control over text styling with gradients, shadows, and advanced effects

16

- Text content changes frequently at runtime

17

- You want pixel-perfect text rendering across all platforms

18

- Working with single-language applications where font loading is not a concern

19

20

**Use BitmapText when:**

21

- Performance is critical (games, animations, many text objects)

22

- Text content changes frequently but styling remains consistent

23

- Working with known character sets (games, UI elements)

24

- Targeting lower-end devices where canvas text rendering may be slow

25

26

**Use HTMLText when:**

27

- You need rich text formatting with multiple styles in one text object

28

- Working with complex layouts, inline images, or web-like text features

29

- Need precise typography control using CSS

30

- Rendering user-generated content with HTML markup

31

32

## API Reference

33

34

### Text { .api }

35

36

Canvas-based text rendering with comprehensive styling options and real-time updates.

37

38

```typescript

39

class Text extends Sprite

40

```

41

42

#### Constructor

43

44

```typescript

45

new Text(text?: string | number, style?: Partial<ITextStyle> | TextStyle, canvas?: ICanvas)

46

```

47

48

- **`text`** - The string to display (supports `\n` for line breaks)

49

- **`style`** - The style parameters (see TextStyle)

50

- **`canvas`** - Optional custom canvas element for drawing

51

52

#### Properties

53

54

- **`text: string`** - The text content to display

55

- **`style: TextStyle`** - The TextStyle object controlling appearance

56

- **`resolution: number`** - The resolution/device pixel ratio for rendering

57

- **`canvas: ICanvas`** - The canvas element used for text rendering (readonly)

58

- **`context: ICanvasRenderingContext2D`** - The 2D rendering context (readonly)

59

60

#### Static Properties

61

62

- **`Text.defaultAutoResolution: boolean`** - Whether resolution matches renderer automatically

63

- **`Text.defaultResolution: number`** - Default resolution when auto-resolution is disabled

64

65

#### Methods

66

67

- **`updateText(respectDirty: boolean): void`** - Renders text to canvas and updates texture

68

- **`destroy(options?: IDestroyOptions | boolean): void`** - Destroys the text object and cleans up resources

69

70

### TextStyle { .api }

71

72

Comprehensive styling interface for canvas-based text rendering.

73

74

```typescript

75

class TextStyle implements ITextStyle

76

interface ITextStyle

77

```

78

79

#### Font Properties

80

81

- **`fontFamily: string | string[]`** - Font family name(s), fallbacks supported

82

- **`fontSize: number | string`** - Font size in pixels or CSS units ('26px', '20pt', '160%', '1.6em')

83

- **`fontStyle: 'normal' | 'italic' | 'oblique'`** - Font style

84

- **`fontVariant: 'normal' | 'small-caps'`** - Font variant

85

- **`fontWeight: 'normal' | 'bold' | 'bolder' | 'lighter' | '100'-'900'`** - Font weight

86

87

#### Appearance Properties

88

89

- **`fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern`** - Fill color or gradient

90

- **`stroke: string | number`** - Stroke color for text outline

91

- **`strokeThickness: number`** - Thickness of the stroke outline

92

93

#### Layout Properties

94

95

- **`align: 'left' | 'center' | 'right' | 'justify'`** - Text alignment for multiline text

96

- **`wordWrap: boolean`** - Enable automatic word wrapping

97

- **`wordWrapWidth: number`** - Maximum width before wrapping occurs

98

- **`breakWords: boolean`** - Allow breaking words when wrapping

99

- **`whiteSpace: 'normal' | 'pre' | 'pre-line'`** - How to handle newlines and spaces

100

101

#### Spacing Properties

102

103

- **`letterSpacing: number`** - Additional space between characters

104

- **`lineHeight: number`** - Vertical space that each line uses

105

- **`leading: number`** - Additional space between lines

106

- **`padding: number`** - Padding around text to prevent clipping

107

108

#### Gradient Properties

109

110

- **`fillGradientType: TEXT_GRADIENT`** - Type of gradient (LINEAR_VERTICAL, LINEAR_HORIZONTAL)

111

- **`fillGradientStops: number[]`** - Color stop positions for gradients (0-1)

112

113

#### Drop Shadow Properties

114

115

- **`dropShadow: boolean`** - Enable drop shadow

116

- **`dropShadowColor: string | number`** - Shadow color

117

- **`dropShadowAlpha: number`** - Shadow opacity (0-1)

118

- **`dropShadowAngle: number`** - Shadow angle in radians

119

- **`dropShadowBlur: number`** - Shadow blur radius

120

- **`dropShadowDistance: number`** - Shadow offset distance

121

122

#### Advanced Properties

123

124

- **`textBaseline: 'alphabetic' | 'top' | 'hanging' | 'middle' | 'ideographic' | 'bottom'`** - Text baseline

125

- **`lineJoin: 'miter' | 'round' | 'bevel'`** - Line join style for strokes

126

- **`miterLimit: number`** - Miter limit for sharp corners

127

- **`trim: boolean`** - Remove transparent borders from texture

128

129

#### Methods

130

131

- **`clone(): TextStyle`** - Create a copy of the style

132

- **`reset(): void`** - Reset all properties to defaults

133

- **`toFontString(): string`** - Generate CSS font string

134

135

### BitmapText { .api }

136

137

High-performance text rendering using pre-generated bitmap fonts.

138

139

```typescript

140

class BitmapText extends Container

141

```

142

143

#### Constructor

144

145

```typescript

146

new BitmapText(text: string, style: Partial<IBitmapTextStyle>)

147

```

148

149

- **`text`** - Text string to display

150

- **`style`** - Bitmap text style options

151

152

#### Properties

153

154

- **`text: string`** - The text content

155

- **`fontName: string`** - Name of the installed BitmapFont

156

- **`fontSize: number`** - Font size (scales the bitmap font)

157

- **`align: TextStyleAlign`** - Text alignment

158

- **`tint: ColorSource`** - Color tint applied to text

159

- **`letterSpacing: number`** - Additional spacing between characters

160

- **`maxWidth: number`** - Maximum width before line wrapping (0 to disable)

161

- **`anchor: ObservablePoint`** - Anchor point for positioning

162

- **`resolution: number`** - Rendering resolution

163

- **`roundPixels: boolean`** - Round positions to avoid sub-pixel rendering

164

165

#### Readonly Properties

166

167

- **`textWidth: number`** - Measured width of the text

168

- **`textHeight: number`** - Measured height of the text

169

- **`maxLineHeight: number`** - Maximum line height for vertical alignment

170

171

#### Methods

172

173

- **`updateText(): void`** - Rebuild the text rendering (called automatically)

174

- **`destroy(options?: boolean | IDestroyOptions): void`** - Clean up resources

175

176

### BitmapTextStyle { .api }

177

178

Style interface for bitmap text rendering.

179

180

```typescript

181

interface IBitmapTextStyle

182

```

183

184

#### Properties

185

186

- **`fontName: string`** - Name of the BitmapFont to use

187

- **`fontSize?: number`** - Font size (defaults to BitmapFont size)

188

- **`tint?: ColorSource`** - Text color tint (default: 0xFFFFFF)

189

- **`align?: 'left' | 'center' | 'right' | 'justify'`** - Text alignment (default: 'left')

190

- **`letterSpacing?: number`** - Letter spacing (default: 0)

191

- **`maxWidth?: number`** - Maximum width for wrapping (default: 0)

192

193

### BitmapFont { .api }

194

195

Manages bitmap font data and provides font generation capabilities.

196

197

```typescript

198

class BitmapFont

199

```

200

201

#### Static Properties

202

203

- **`BitmapFont.available: Dict<BitmapFont>`** - Registry of installed fonts

204

- **`BitmapFont.ALPHA: string[][]`** - Character set with alphabetic characters

205

- **`BitmapFont.NUMERIC: string[][]`** - Character set with numeric characters

206

- **`BitmapFont.ALPHANUMERIC: string[][]`** - Combined alpha and numeric characters

207

- **`BitmapFont.ASCII: string[][]`** - Full ASCII character set

208

209

#### Properties

210

211

- **`font: string`** - Font family name

212

- **`size: number`** - Original font size in pixels

213

- **`lineHeight: number`** - Line height in pixels

214

- **`chars: Dict<IBitmapFontCharacter>`** - Character data mapping

215

- **`pageTextures: Dict<Texture>`** - Texture pages containing glyphs

216

- **`distanceFieldRange: number`** - Range for distance field fonts

217

- **`distanceFieldType: string`** - Type of distance field ('none', 'sdf', 'msdf', 'mtsdf')

218

219

#### Static Methods

220

221

- **`BitmapFont.from(name: string, textStyle: TextStyle | ITextStyle, options?: IBitmapFontOptions): BitmapFont`** - Generate bitmap font from text style

222

- **`BitmapFont.install(...fonts: BitmapFontInstallOptions[]): void`** - Install bitmap fonts

223

- **`BitmapFont.uninstall(name: string): void`** - Remove installed font

224

225

### HTMLText { .api }

226

227

CSS-based text rendering with rich HTML markup support.

228

229

```typescript

230

class HTMLText extends Sprite

231

```

232

233

#### Constructor

234

235

```typescript

236

new HTMLText(text?: string, style?: HTMLTextStyle | TextStyle | Partial<ITextStyle>)

237

```

238

239

- **`text`** - HTML text content

240

- **`style`** - Style configuration (HTMLTextStyle recommended)

241

242

#### Properties

243

244

- **`text: string`** - HTML content (supports markup tags)

245

- **`style: HTMLTextStyle`** - Style object controlling appearance

246

- **`resolution: number`** - Rendering resolution

247

- **`maxWidth: number`** - Maximum content width in pixels

248

- **`maxHeight: number`** - Maximum content height in pixels

249

- **`source: HTMLImageElement`** - Underlying image element (readonly)

250

251

#### Static Properties

252

253

- **`HTMLText.defaultMaxWidth: number`** - Default maximum width (2024)

254

- **`HTMLText.defaultMaxHeight: number`** - Default maximum height (2024)

255

- **`HTMLText.defaultResolution: number`** - Default resolution

256

- **`HTMLText.defaultAutoResolution: boolean`** - Auto resolution matching

257

258

#### Methods

259

260

- **`measureText(overrides?: {text?, style?, resolution?}): ISize`** - Calculate text dimensions without rendering

261

- **`updateText(respectDirty?: boolean): Promise<void>`** - Asynchronously update text rendering

262

- **`destroy(options?: boolean | IDestroyOptions): void`** - Clean up resources

263

264

### HTMLTextStyle { .api }

265

266

Advanced styling for HTML-based text rendering with CSS capabilities.

267

268

```typescript

269

class HTMLTextStyle extends TextStyle

270

interface IHTMLTextStyle extends Omit<ITextStyle, 'whiteSpace'|'fillGradientStops'|'fillGradientType'|'miterLimit'|'textBaseline'|'trim'|'leading'|'lineJoin'>

271

```

272

273

#### Enhanced Properties

274

275

- **`whiteSpace: 'normal' | 'pre' | 'pre-line' | 'nowrap' | 'pre-wrap'`** - Extended white-space handling

276

277

#### Font Loading

278

279

- **`loadFont(url: string, options?: Partial<IHTMLTextFontOptions>): Promise<void>`** - Load custom fonts

280

- **`cleanFonts(): void`** - Remove loaded fonts and clean up

281

282

#### Style Overrides

283

284

- **`addOverride(...values: string[]): void`** - Add custom CSS property overrides

285

- **`removeOverride(...values: string[]): void`** - Remove CSS property overrides

286

- **`stylesheet: string`** - Internal CSS stylesheet content

287

288

#### CSS Generation

289

290

- **`toCSS(scale: number): string`** - Generate CSS styles for the element

291

- **`toGlobalCSS(): string`** - Generate global CSS including font-face rules

292

293

#### Static Methods

294

295

- **`HTMLTextStyle.from(originalStyle: TextStyle | Partial<IHTMLTextStyle>): HTMLTextStyle`** - Convert TextStyle to HTMLTextStyle

296

297

#### Font Options Interface

298

299

```typescript

300

interface IHTMLTextFontOptions

301

{

302

weight?: TextStyleFontWeight;

303

style?: TextStyleFontStyle;

304

family?: string;

305

display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional';

306

}

307

```

308

309

### TextMetrics { .api }

310

311

Utility class for measuring and analyzing text dimensions and properties.

312

313

```typescript

314

class TextMetrics

315

```

316

317

#### Properties

318

319

- **`text: string`** - The measured text

320

- **`style: TextStyle`** - The style used for measurement

321

- **`width: number`** - Total text width

322

- **`height: number`** - Total text height

323

- **`lines: string[]`** - Array of text lines after wrapping

324

- **`lineWidths: number[]`** - Width of each line

325

- **`lineHeight: number`** - Calculated line height

326

- **`maxLineWidth: number`** - Width of the widest line

327

- **`fontProperties: IFontMetrics`** - Font metrics (ascent, descent, fontSize)

328

329

#### Static Methods

330

331

- **`TextMetrics.measureText(text: string, style: TextStyle, wordWrap?: boolean, canvas?: ICanvas): TextMetrics`** - Measure text with given style

332

- **`TextMetrics.measureFont(font: string): IFontMetrics`** - Measure font metrics

333

- **`TextMetrics.clearMetrics(font?: string): void`** - Clear cached font metrics

334

335

#### Static Properties

336

337

- **`TextMetrics.experimentalLetterSpacing: boolean`** - Use native letter-spacing API when available

338

- **`TextMetrics.experimentalLetterSpacingSupported: boolean`** - Check if native letter-spacing is supported

339

340

## Usage Examples

341

342

### Basic Text Rendering

343

344

Create simple text with styling:

345

346

```typescript

347

import { Text, TextStyle } from 'pixi.js';

348

349

// Basic text with inline styling

350

const text = new Text('Hello World', {

351

fontFamily: 'Arial',

352

fontSize: 24,

353

fill: 0xff1010,

354

align: 'center',

355

});

356

357

// Text with advanced styling

358

const styledText = new Text('Advanced Text', new TextStyle({

359

fontFamily: ['Helvetica', 'Arial', 'sans-serif'],

360

fontSize: 36,

361

fontWeight: 'bold',

362

fill: ['#ffffff', '#00ff99'], // Gradient from white to green

363

stroke: '#4a1850',

364

strokeThickness: 5,

365

dropShadow: true,

366

dropShadowColor: '#000000',

367

dropShadowBlur: 4,

368

dropShadowAngle: Math.PI / 6,

369

dropShadowDistance: 6,

370

wordWrap: true,

371

wordWrapWidth: 440,

372

}));

373

```

374

375

### Performance-Optimized Bitmap Text

376

377

Using bitmap fonts for high-performance scenarios:

378

379

```typescript

380

import { BitmapFont, BitmapText } from 'pixi.js';

381

382

// Generate bitmap font from text style

383

BitmapFont.from('MyFont', {

384

fontFamily: 'Arial',

385

fontSize: 32,

386

fill: 0xffffff,

387

}, {

388

chars: BitmapFont.ALPHANUMERIC,

389

resolution: 1,

390

padding: 4,

391

});

392

393

// Create high-performance text

394

const bitmapText = new BitmapText('Score: 0', {

395

fontName: 'MyFont',

396

fontSize: 32,

397

tint: 0xff0000,

398

align: 'center',

399

});

400

401

// Efficient updates (no texture regeneration)

402

function updateScore(score: number) {

403

bitmapText.text = `Score: ${score}`;

404

}

405

```

406

407

### Rich HTML Text Formatting

408

409

HTML text with CSS styling and custom fonts:

410

411

```typescript

412

import { HTMLText, HTMLTextStyle } from 'pixi.js';

413

414

// Load custom font

415

const style = new HTMLTextStyle({

416

fontSize: 20,

417

fill: '#333333',

418

wordWrap: true,

419

wordWrapWidth: 300,

420

});

421

422

await style.loadFont('/fonts/custom-font.woff2', {

423

family: 'CustomFont',

424

weight: 'normal',

425

});

426

427

// Create rich text with HTML markup

428

const htmlText = new HTMLText(

429

'This is <b>bold</b> and <i>italic</i> text with <span style="color: red;">colored</span> words.',

430

style

431

);

432

433

// CSS overrides for advanced styling

434

style.addOverride('text-shadow: 2px 2px 4px rgba(0,0,0,0.3)');

435

style.addOverride('background: linear-gradient(45deg, #ff0000, #0000ff)');

436

```

437

438

### Dynamic Text Updates

439

440

Efficient text updating patterns:

441

442

```typescript

443

// Text: Good for infrequent updates with style changes

444

const dynamicText = new Text('Initial Text', style);

445

446

function updateTextContent() {

447

// Texture regenerated on each update

448

dynamicText.text = `Time: ${Date.now()}`;

449

dynamicText.style.fill = Math.random() * 0xFFFFFF;

450

}

451

452

// BitmapText: Optimal for frequent updates with consistent style

453

const gameText = new BitmapText('Lives: 3', { fontName: 'GameFont' });

454

455

function updateGameState() {

456

// No texture regeneration, just vertex updates

457

gameText.text = `Lives: ${player.lives}`;

458

gameText.tint = player.lives > 1 ? 0xFFFFFF : 0xFF0000;

459

}

460

461

// HTMLText: Best for rich content that changes occasionally

462

const contentText = new HTMLText('<p>Loading...</p>', htmlStyle);

463

464

async function loadContent() {

465

const content = await fetchContent();

466

contentText.text = `<h2>${content.title}</h2><p>${content.body}</p>`;

467

}

468

```

469

470

### Text Measurement and Bounds

471

472

Working with text dimensions and positioning:

473

474

```typescript

475

import { TextMetrics } from 'pixi.js';

476

477

// Measure text before creating

478

const metrics = TextMetrics.measureText('Sample Text', style);

479

console.log(`Text size: ${metrics.width}x${metrics.height}`);

480

console.log(`Lines: ${metrics.lines.length}`);

481

482

// Center text using measured bounds

483

const text = new Text('Centered Text', style);

484

text.anchor.set(0.5); // Center anchor

485

text.x = app.screen.width / 2;

486

text.y = app.screen.height / 2;

487

488

// Responsive text fitting

489

function fitTextToWidth(text: Text, maxWidth: number) {

490

const style = text.style;

491

let fontSize = parseInt(style.fontSize as string);

492

493

while (fontSize > 8) {

494

style.fontSize = fontSize;

495

text.updateText(false);

496

497

if (text.width <= maxWidth) break;

498

fontSize -= 2;

499

}

500

}

501

```

502

503

## Performance Guidance

504

505

### Text Rendering Performance

506

507

**Canvas Text (Text class):**

508

- Each text object creates its own texture

509

- Texture regeneration occurs on every text or style change

510

- Best for: < 50 text objects with infrequent updates

511

- Memory usage: High (one texture per text object)

512

513

**Bitmap Text (BitmapText class):**

514

- Shares texture atlas across all instances

515

- Only vertex data updates when text changes

516

- Best for: 100s-1000s of text objects with frequent updates

517

- Memory usage: Low (shared texture atlas)

518

519

**HTML Text (HTMLText class):**

520

- Asynchronous rendering via SVG foreignObject

521

- Supports rich markup and CSS styling

522

- Best for: Complex formatted text with occasional updates

523

- Performance: Moderate (DOM/SVG overhead)

524

525

### Memory Optimization

526

527

```typescript

528

// Optimize bitmap font texture size

529

BitmapFont.from('OptimizedFont', style, {

530

chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,!?',

531

textureWidth: 256, // Smaller texture for limited character set

532

textureHeight: 256,

533

padding: 2, // Minimal padding

534

});

535

536

// Reuse TextStyle objects

537

const sharedStyle = new TextStyle({ fontSize: 16, fill: 0xFFFFFF });

538

const text1 = new Text('Text 1', sharedStyle);

539

const text2 = new Text('Text 2', sharedStyle);

540

541

// Clean up unused fonts

542

BitmapFont.uninstall('UnusedFont');

543

htmlStyle.cleanFonts();

544

```

545

546

### Rendering Optimization

547

548

```typescript

549

// Disable auto-resolution for consistent performance

550

Text.defaultAutoResolution = false;

551

Text.defaultResolution = 1;

552

553

// Use appropriate resolution for text clarity

554

const highDPIText = new Text('Sharp Text', style);

555

highDPIText.resolution = 2; // 2x resolution for retina displays

556

557

// Batch similar text objects

558

const textContainer = new Container();

559

textContainer.addChild(text1, text2, text3);

560

// All children rendered together

561

562

// Cache static text as sprites

563

const staticText = new Text('Static Label', style);

564

staticText.updateText(false); // Force texture generation

565

const sprite = new Sprite(staticText.texture);

566

// Use sprite instead of text for better performance

567

```

568

569

## Platform Considerations

570

571

### Browser Support

572

573

**Text (Canvas):** Universal support across all browsers and platforms

574

**BitmapText:** Universal support, optimal for WebGL contexts

575

**HTMLText:** Requires SVG foreignObject support (not supported in Internet Explorer)

576

577

### Mobile Performance

578

579

- Use BitmapText for mobile games requiring many text objects

580

- Reduce bitmap font texture sizes for memory-constrained devices

581

- Consider Text.defaultResolution = 1 for better performance on low-end devices

582

- HTMLText may have performance implications on older mobile browsers

583

584

### Font Loading

585

586

```typescript

587

// Preload web fonts before creating text

588

await document.fonts.load('16px CustomFont');

589

const text = new Text('Custom Font Text', {

590

fontFamily: 'CustomFont, Arial',

591

fontSize: 16,

592

});

593

594

// For HTMLText, use the built-in font loader

595

const htmlStyle = new HTMLTextStyle();

596

await htmlStyle.loadFont('/fonts/custom.woff2');

597

```