or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdtext-measurement.mdtext-rendering.mdtext-styling.md

text-measurement.mddocs/

0

# Text Measurement

1

2

Advanced text measurement utilities for calculating dimensions, font properties, and text layout analysis. The TextMetrics class provides comprehensive text measurement capabilities including word wrapping, multi-line analysis, and font metrics calculation.

3

4

## Capabilities

5

6

### TextMetrics Constructor

7

8

Creates a TextMetrics instance with pre-calculated measurement data.

9

10

```typescript { .api }

11

/**

12

* Creates a TextMetrics object with measurement results

13

* @param text - The measured text string

14

* @param style - The TextStyle used for measurement

15

* @param width - Total measured width

16

* @param height - Total measured height

17

* @param lines - Array of text lines after wrapping

18

* @param lineWidths - Width of each individual line

19

* @param lineHeight - Line height used for measurement

20

* @param maxLineWidth - Maximum width among all lines

21

* @param fontProperties - Font metrics data

22

*/

23

constructor(

24

text: string,

25

style: TextStyle,

26

width: number,

27

height: number,

28

lines: string[],

29

lineWidths: number[],

30

lineHeight: number,

31

maxLineWidth: number,

32

fontProperties: IFontMetrics

33

);

34

```

35

36

### Text Measurement

37

38

Main static method for measuring text dimensions with optional word wrapping.

39

40

```typescript { .api }

41

/**

42

* Measures text dimensions and returns comprehensive metrics

43

* @param text - Text string to measure

44

* @param style - TextStyle configuration for measurement

45

* @param wordWrap - Override word wrap setting (uses style.wordWrap if undefined)

46

* @param canvas - Optional canvas for measurement (uses internal canvas if not provided)

47

* @returns Complete TextMetrics with dimensions and line data

48

*/

49

static measureText(

50

text: string,

51

style: TextStyle,

52

wordWrap?: boolean,

53

canvas?: HTMLCanvasElement | OffscreenCanvas

54

): TextMetrics;

55

```

56

57

**Usage Examples:**

58

59

```typescript

60

import { TextMetrics, TextStyle } from "@pixi/text";

61

62

const style = new TextStyle({

63

fontSize: 24,

64

fontFamily: 'Arial',

65

wordWrap: true,

66

wordWrapWidth: 300

67

});

68

69

// Basic measurement

70

const metrics = TextMetrics.measureText('Hello World', style);

71

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

72

73

// Measure with custom word wrap setting

74

const noWrapMetrics = TextMetrics.measureText(

75

'This is a long text that would normally wrap',

76

style,

77

false // Disable word wrap for this measurement

78

);

79

80

// Measure with custom canvas

81

const canvas = document.createElement('canvas');

82

const customMetrics = TextMetrics.measureText('Custom canvas', style, true, canvas);

83

```

84

85

### Font Metrics Calculation

86

87

Static method for calculating font-specific metrics like ascent, descent, and font size.

88

89

```typescript { .api }

90

/**

91

* Calculates font metrics for a given font string

92

* @param font - CSS font string (e.g., "24px Arial")

93

* @returns Font metrics with ascent, descent, and fontSize

94

*/

95

static measureFont(font: string): IFontMetrics;

96

97

interface IFontMetrics {

98

/** Distance from baseline to top of tallest characters */

99

ascent: number;

100

/** Distance from baseline to bottom of lowest characters */

101

descent: number;

102

/** Total font height (ascent + descent) */

103

fontSize: number;

104

}

105

```

106

107

**Usage Examples:**

108

109

```typescript

110

// Measure font metrics

111

const fontMetrics = TextMetrics.measureFont('24px Arial');

112

console.log(`Ascent: ${fontMetrics.ascent}`);

113

console.log(`Descent: ${fontMetrics.descent}`);

114

console.log(`Font size: ${fontMetrics.fontSize}`);

115

116

// Use with TextStyle

117

const style = new TextStyle({ fontSize: 32, fontFamily: 'Helvetica' });

118

const fontString = style.toFontString();

119

const metrics = TextMetrics.measureFont(fontString);

120

```

121

122

### Metrics Cache Management

123

124

Static methods for managing the internal font metrics cache to optimize performance.

125

126

```typescript { .api }

127

/**

128

* Clears cached font metrics

129

* @param font - Specific font to clear, or empty string to clear all

130

*/

131

static clearMetrics(font?: string): void;

132

```

133

134

**Usage Examples:**

135

136

```typescript

137

// Clear all cached metrics

138

TextMetrics.clearMetrics();

139

140

// Clear specific font metrics

141

TextMetrics.clearMetrics('24px Arial');

142

143

// Clear with empty string (same as clearMetrics())

144

TextMetrics.clearMetrics('');

145

```

146

147

### Measurement Data Properties

148

149

Instance properties containing the measurement results.

150

151

```typescript { .api }

152

/**

153

* The original text that was measured

154

*/

155

text: string;

156

157

/**

158

* The TextStyle used for measurement

159

*/

160

style: TextStyle;

161

162

/**

163

* Total width including effects like stroke and drop shadow

164

*/

165

width: number;

166

167

/**

168

* Total height including line spacing and effects

169

*/

170

height: number;

171

172

/**

173

* Array of text lines after word wrapping and line breaks

174

*/

175

lines: string[];

176

177

/**

178

* Width of each individual line

179

*/

180

lineWidths: number[];

181

182

/**

183

* Line height value used for measurement

184

*/

185

lineHeight: number;

186

187

/**

188

* Maximum width among all lines

189

*/

190

maxLineWidth: number;

191

192

/**

193

* Font metrics data for the measured font

194

*/

195

fontProperties: IFontMetrics;

196

```

197

198

**Usage Examples:**

199

200

```typescript

201

const metrics = TextMetrics.measureText('Multi-line\ntext sample', style);

202

203

// Access measurement data

204

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

205

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

206

console.log(`Lines: ${metrics.lines.join(', ')}`);

207

console.log(`Line widths: ${metrics.lineWidths.join(', ')}`);

208

console.log(`Max line width: ${metrics.maxLineWidth}`);

209

console.log(`Font ascent: ${metrics.fontProperties.ascent}`);

210

```

211

212

### Text Processing Utilities

213

214

Static utility methods for text analysis and processing.

215

216

```typescript { .api }

217

/**

218

* Determines if a character is a breaking whitespace

219

* @param char - Character to check

220

* @param nextChar - Optional next character for context

221

* @returns True if character should break lines/words

222

*/

223

static isBreakingSpace(char: string, nextChar?: string): boolean;

224

225

/**

226

* Determines if words can be broken at character level

227

* @param token - Word/token to check

228

* @param breakWords - Style setting for word breaking

229

* @returns True if word can be broken

230

*/

231

static canBreakWords(token: string, breakWords: boolean): boolean;

232

233

/**

234

* Determines if specific characters can be broken between

235

* @param char - Current character

236

* @param nextChar - Next character

237

* @param token - Full word/token

238

* @param index - Character position in token

239

* @param breakWords - Style setting for word breaking

240

* @returns True if break is allowed between characters

241

*/

242

static canBreakChars(

243

char: string,

244

nextChar: string,

245

token: string,

246

index: number,

247

breakWords: boolean

248

): boolean;

249

250

/**

251

* Splits a token into individual characters for word breaking

252

* @param token - Token to split

253

* @returns Array of character strings

254

*/

255

static wordWrapSplit(token: string): string[];

256

```

257

258

**Usage Examples:**

259

260

```typescript

261

// Check breaking spaces

262

const isSpace = TextMetrics.isBreakingSpace(' ');

263

const isTab = TextMetrics.isBreakingSpace('\t');

264

265

// Check word breaking

266

const canBreak = TextMetrics.canBreakWords('supercalifragilisticexpialidocious', true);

267

268

// Check character breaking

269

const canBreakHere = TextMetrics.canBreakChars('a', 'b', 'word', 0, true);

270

271

// Split token for breaking

272

const chars = TextMetrics.wordWrapSplit('hello');

273

console.log(chars); // ['h', 'e', 'l', 'l', 'o']

274

```

275

276

### Canvas Access

277

278

Static properties providing access to the internal measurement canvas and context.

279

280

```typescript { .api }

281

/**

282

* Internal canvas used for text measurement

283

* Automatically created as HTMLCanvas or OffscreenCanvas based on environment

284

*/

285

static get _canvas(): HTMLCanvasElement | OffscreenCanvas;

286

287

/**

288

* Internal 2D context for measurement operations

289

*/

290

static get _context(): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;

291

```

292

293

**Usage Examples:**

294

295

```typescript

296

// Access measurement canvas

297

const measurementCanvas = TextMetrics._canvas;

298

console.log(`Canvas size: ${measurementCanvas.width}x${measurementCanvas.height}`);

299

300

// Access measurement context (advanced usage)

301

const ctx = TextMetrics._context;

302

ctx.font = '16px Arial';

303

const width = ctx.measureText('test').width;

304

```

305

306

### Measurement Constants

307

308

Static constants used for font metrics calculation.

309

310

```typescript { .api }

311

/**

312

* String used for font metrics calculation

313

* Contains tall characters to measure full font height

314

*/

315

static METRICS_STRING: string; // '|ÉqÅ'

316

317

/**

318

* Baseline symbol for font measurement

319

*/

320

static BASELINE_SYMBOL: string; // 'M'

321

322

/**

323

* Multiplier for baseline calculation

324

*/

325

static BASELINE_MULTIPLIER: number; // 1.4

326

327

/**

328

* Multiplier for canvas height during measurement

329

*/

330

static HEIGHT_MULTIPLIER: number; // 2.0

331

```

332

333

**Usage Examples:**

334

335

```typescript

336

// Access measurement constants

337

console.log(`Metrics string: ${TextMetrics.METRICS_STRING}`);

338

console.log(`Baseline symbol: ${TextMetrics.BASELINE_SYMBOL}`);

339

console.log(`Baseline multiplier: ${TextMetrics.BASELINE_MULTIPLIER}`);

340

```

341

342

## Advanced Usage Examples

343

344

**Pre-calculating Text Dimensions:**

345

346

```typescript

347

import { TextStyle, TextMetrics } from "@pixi/text";

348

349

const styles = [

350

new TextStyle({ fontSize: 16 }),

351

new TextStyle({ fontSize: 24 }),

352

new TextStyle({ fontSize: 32 })

353

];

354

355

const texts = ['Small', 'Medium', 'Large'];

356

357

// Pre-calculate dimensions for layout

358

const measurements = texts.map((text, i) => ({

359

text,

360

style: styles[i],

361

metrics: TextMetrics.measureText(text, styles[i])

362

}));

363

364

// Use measurements for layout calculations

365

let totalHeight = 0;

366

measurements.forEach(({ metrics }) => {

367

totalHeight += metrics.height + 10; // 10px spacing

368

});

369

```

370

371

**Dynamic Font Loading with Metrics:**

372

373

```typescript

374

// Wait for font to load, then measure

375

document.fonts.ready.then(() => {

376

// Clear cached metrics after font loads

377

TextMetrics.clearMetrics();

378

379

const style = new TextStyle({

380

fontFamily: 'MyCustomFont',

381

fontSize: 24

382

});

383

384

const metrics = TextMetrics.measureText('Custom font text', style);

385

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

386

});

387

```

388

389

**Word Wrap Analysis:**

390

391

```typescript

392

const longText = 'This is a very long text that will be wrapped across multiple lines when the word wrap width is set to a specific value.';

393

394

const style = new TextStyle({

395

fontSize: 16,

396

wordWrap: true,

397

wordWrapWidth: 200

398

});

399

400

const metrics = TextMetrics.measureText(longText, style);

401

402

console.log(`Original text length: ${longText.length}`);

403

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

404

console.log(`Lines:`);

405

metrics.lines.forEach((line, i) => {

406

console.log(` ${i + 1}: "${line}" (width: ${metrics.lineWidths[i]})`);

407

});

408

```

409

410

**Performance Optimization:**

411

412

```typescript

413

// Batch measurements for better performance

414

const textsToMeasure = ['Text 1', 'Text 2', 'Text 3'];

415

const style = new TextStyle({ fontSize: 18 });

416

417

// Use the same canvas for all measurements

418

const canvas = document.createElement('canvas');

419

const measurements = textsToMeasure.map(text =>

420

TextMetrics.measureText(text, style, undefined, canvas)

421

);

422

423

// Clear metrics cache when done

424

TextMetrics.clearMetrics();

425

```