0
# Utilities and Helpers
1
2
Browser detection, color management, utility functions, debugging tools, and performance optimization helpers. These utilities provide essential functionality for feature detection, data manipulation, and application optimization.
3
4
## Capabilities
5
6
### Browser Detection
7
8
Functions for detecting browser capabilities and device types.
9
10
```typescript { .api }
11
/**
12
* Check if running on mobile device
13
* @returns True if mobile device detected
14
*/
15
function isMobile(): boolean;
16
17
/**
18
* Check if WebGL is supported
19
* @returns True if WebGL is supported
20
*/
21
function isWebGLSupported(): boolean;
22
23
/**
24
* Check if WebGPU is supported
25
* @returns Promise resolving to WebGPU support status
26
*/
27
function isWebGPUSupported(): Promise<boolean>;
28
29
/**
30
* Check if running in Safari browser
31
* @returns True if Safari detected
32
*/
33
function isSafari(): boolean;
34
35
/**
36
* Check if unsafe eval is supported
37
* @returns True if eval is available
38
*/
39
function unsafeEvalSupported(): boolean;
40
41
/**
42
* Detect video alpha mode support
43
* @returns Promise resolving to alpha mode support
44
*/
45
function detectVideoAlphaMode(): Promise<boolean>;
46
```
47
48
### Color Management
49
50
Comprehensive color class with multiple format support and manipulation.
51
52
```typescript { .api }
53
/**
54
* Color class supporting multiple formats and operations
55
*/
56
class Color {
57
constructor(value?: ColorSource);
58
59
/** Numeric color value */
60
readonly value: number;
61
62
/** Alpha channel (0-1) */
63
readonly alpha: number;
64
65
/**
66
* Set color value
67
* @param value - Color in any supported format
68
* @returns This color instance
69
*/
70
setValue(value: ColorSource): this;
71
72
/**
73
* Set alpha channel
74
* @param alpha - Alpha value (0-1)
75
* @returns This color instance
76
*/
77
setAlpha(alpha: number): this;
78
79
/**
80
* Convert to hex string
81
* @returns Hex color string (e.g., "#ff0000")
82
*/
83
toHex(): string;
84
85
/**
86
* Convert to RGBA array
87
* @returns RGBA values [r, g, b, a] (0-1)
88
*/
89
toRgba(): [number, number, number, number];
90
91
/**
92
* Convert to RGB object
93
* @returns RGB object with r, g, b properties (0-255)
94
*/
95
toRgb(): { r: number; g: number; b: number };
96
97
/**
98
* Convert to HSL array
99
* @returns HSL values [h, s, l] (h: 0-360, s,l: 0-1)
100
*/
101
toHsl(): [number, number, number];
102
103
/**
104
* Convert to HSV array
105
* @returns HSV values [h, s, v] (h: 0-360, s,v: 0-1)
106
*/
107
toHsv(): [number, number, number];
108
109
/**
110
* Multiply color by another color
111
* @param value - Color to multiply by
112
* @returns New color result
113
*/
114
multiply(value: ColorSource): Color;
115
116
/**
117
* Add color to another color
118
* @param value - Color to add
119
* @returns New color result
120
*/
121
add(value: ColorSource): Color;
122
123
/**
124
* Subtract color from another color
125
* @param value - Color to subtract
126
* @returns New color result
127
*/
128
subtract(value: ColorSource): Color;
129
130
/**
131
* Brighten color
132
* @param amount - Brighten amount (0-1)
133
* @returns New brightened color
134
*/
135
brighten(amount: number): Color;
136
137
/**
138
* Darken color
139
* @param amount - Darken amount (0-1)
140
* @returns New darkened color
141
*/
142
darken(amount: number): Color;
143
144
/**
145
* Desaturate color
146
* @param amount - Desaturation amount (0-1)
147
* @returns New desaturated color
148
*/
149
desaturate(amount: number): Color;
150
151
/**
152
* Get grayscale version
153
* @returns Grayscale color
154
*/
155
grayscale(): Color;
156
157
/**
158
* Clone color
159
* @returns New color with same values
160
*/
161
clone(): Color;
162
163
/**
164
* Check if value is color-like
165
* @param value - Value to check
166
* @returns True if color-like
167
*/
168
static isColorLike(value: any): value is ColorSource;
169
170
/**
171
* Convert hex string to number
172
* @param hex - Hex string
173
* @returns Numeric color value
174
*/
175
static hexToNumber(hex: string): number;
176
177
/**
178
* Convert number to hex string
179
* @param value - Numeric color
180
* @returns Hex string
181
*/
182
static numberToHex(value: number): string;
183
184
/** Shared color instance for temp calculations */
185
static readonly shared: Color;
186
}
187
188
/**
189
* Color source types
190
*/
191
type ColorSource =
192
| number // 0xff0000
193
| string // "#ff0000", "red", "rgb(255,0,0)"
194
| Color // Color instance
195
| [number, number, number] // RGB array
196
| [number, number, number, number] // RGBA array
197
| { r: number; g: number; b: number; a?: number }; // RGB object
198
```
199
200
### Unique ID Generation
201
202
System for generating unique identifiers.
203
204
```typescript { .api }
205
/**
206
* Generate unique identifier
207
* @returns Unique number ID
208
*/
209
function uid(): number;
210
211
/**
212
* Create ID from string
213
* @param value - String to convert
214
* @returns Numeric ID
215
*/
216
function createIdFromString(value: string): number;
217
```
218
219
### Data Utilities
220
221
Utilities for data manipulation and management.
222
223
```typescript { .api }
224
/**
225
* ViewableBuffer for efficient data handling
226
*/
227
class ViewableBuffer {
228
constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer, size?: number);
229
230
/** Raw array buffer */
231
readonly rawBinaryData: ArrayBuffer | SharedArrayBuffer;
232
233
/** Uint32 view of buffer */
234
uint32View: Uint32Array;
235
236
/** Float32 view of buffer */
237
float32View: Float32Array;
238
239
/** Buffer size */
240
size: number;
241
242
/**
243
* Destroy buffer and views
244
*/
245
destroy(): void;
246
247
/**
248
* Ensure buffer has minimum size
249
* @param requestedSize - Minimum required size
250
*/
251
ensureCapacity(requestedSize: number): void;
252
}
253
254
/**
255
* Remove items from array
256
* @param arr - Array to modify
257
* @param startIdx - Start index
258
* @param removeCount - Number of items to remove
259
* @returns Modified array
260
*/
261
function removeItems<T>(arr: T[], startIdx: number, removeCount: number): T[];
262
263
/**
264
* Clean/trim array by removing falsy values
265
* @param arr - Array to clean
266
* @returns Cleaned array
267
*/
268
function clean<T>(arr: T[]): T[];
269
270
/**
271
* Update quad bounds efficiently
272
* @param bounds - Bounds to update
273
* @param x1 - First X coordinate
274
* @param y1 - First Y coordinate
275
* @param x2 - Second X coordinate
276
* @param y2 - Second Y coordinate
277
* @param x3 - Third X coordinate
278
* @param y3 - Third Y coordinate
279
* @param x4 - Fourth X coordinate
280
* @param y4 - Fourth Y coordinate
281
*/
282
function updateQuadBounds(bounds: Rectangle, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): void;
283
```
284
285
### Object Pooling
286
287
Memory management through object pooling for performance optimization.
288
289
```typescript { .api }
290
/**
291
* Generic object pool for reusing objects
292
*/
293
class Pool<T> {
294
constructor(ClassType: new () => T, resetFunction?: (item: T) => void);
295
296
/**
297
* Get object from pool
298
* @returns Pooled object
299
*/
300
get(): T;
301
302
/**
303
* Return object to pool
304
* @param item - Object to return
305
*/
306
return(item: T): void;
307
308
/**
309
* Clear all pooled objects
310
*/
311
clear(): void;
312
313
/** Number of objects in pool */
314
readonly count: number;
315
}
316
317
/**
318
* Pool group for managing multiple pools
319
*/
320
class PoolGroup {
321
constructor();
322
323
/**
324
* Get pool for class type
325
* @param ClassType - Class constructor
326
* @param resetFunction - Reset function for objects
327
* @returns Pool instance
328
*/
329
getPool<T>(ClassType: new () => T, resetFunction?: (item: T) => void): Pool<T>;
330
331
/**
332
* Clear all pools
333
*/
334
clear(): void;
335
}
336
```
337
338
### Transform Utilities
339
340
Transform and matrix manipulation utilities.
341
342
```typescript { .api }
343
/**
344
* Transform class for object transformations
345
*/
346
class Transform {
347
constructor();
348
349
/** Local transformation matrix */
350
localTransform: Matrix;
351
352
/** World transformation matrix */
353
worldTransform: Matrix;
354
355
/** Position */
356
position: ObservablePoint;
357
358
/** Scale */
359
scale: ObservablePoint;
360
361
/** Pivot point */
362
pivot: ObservablePoint;
363
364
/** Skew */
365
skew: ObservablePoint;
366
367
/** Rotation in radians */
368
rotation: number;
369
370
/**
371
* Update local transform
372
*/
373
updateLocalTransform(): void;
374
375
/**
376
* Update world transform
377
* @param parentTransform - Parent transform
378
*/
379
updateTransform(parentTransform: Transform): void;
380
381
/**
382
* Set from matrix
383
* @param matrix - Matrix to apply
384
* @returns This transform
385
*/
386
setFromMatrix(matrix: Matrix): this;
387
}
388
```
389
390
### Logging and Debugging
391
392
Debugging utilities and logging functions.
393
394
```typescript { .api }
395
/**
396
* Log warning message
397
* @param message - Warning message
398
* @param ...args - Additional arguments
399
*/
400
function warn(message: string, ...args: any[]): void;
401
402
/**
403
* Show deprecation warning
404
* @param version - Version when deprecated
405
* @param message - Deprecation message
406
* @param ignoreDepth - Stack trace depth to ignore
407
*/
408
function deprecation(version: string, message: string, ignoreDepth?: number): void;
409
410
/**
411
* Log debug information about texture
412
* @param texture - Texture to debug
413
* @param renderer - Renderer instance
414
*/
415
function logDebugTexture(texture: Texture, renderer: Renderer): void;
416
417
/**
418
* Log scene graph structure
419
* @param container - Container to log
420
* @param depth - Current depth level
421
*/
422
function logScene(container: Container, depth?: number): void;
423
```
424
425
### Network Utilities
426
427
Network and URL utilities.
428
429
```typescript { .api }
430
/**
431
* Get resolution from URL
432
* @param url - URL to analyze
433
* @returns Resolution multiplier
434
*/
435
function getResolutionOfUrl(url: string): number;
436
```
437
438
### Canvas Utilities
439
440
Canvas manipulation and measurement utilities.
441
442
```typescript { .api }
443
/**
444
* Get canvas bounding box
445
* @param canvas - Canvas element
446
* @param resolution - Resolution multiplier
447
* @returns Bounding rectangle
448
*/
449
function getCanvasBoundingBox(canvas: HTMLCanvasElement, resolution?: number): Rectangle;
450
```
451
452
### Path Utilities
453
454
Path manipulation and parsing utilities.
455
456
```typescript { .api }
457
/**
458
* Parse path string into components
459
* @param path - Path string
460
* @returns Path components
461
*/
462
function parsePath(path: string): PathComponent[];
463
464
/**
465
* Join path components
466
* @param ...components - Path components to join
467
* @returns Joined path string
468
*/
469
function joinPath(...components: string[]): string;
470
471
interface PathComponent {
472
/** Component type */
473
type: 'directory' | 'file' | 'extension';
474
475
/** Component value */
476
value: string;
477
}
478
```
479
480
**Usage Examples:**
481
482
```typescript
483
import {
484
Color,
485
isMobile,
486
isWebGLSupported,
487
uid,
488
Pool,
489
Transform,
490
warn,
491
getResolutionOfUrl
492
} from 'pixi.js';
493
494
// Browser detection
495
if (isMobile()) {
496
console.log('Running on mobile device');
497
}
498
499
if (await isWebGLSupported()) {
500
console.log('WebGL is supported');
501
}
502
503
// Color manipulation
504
const color = new Color('#ff0000');
505
console.log(color.toHex()); // "#ff0000"
506
console.log(color.toRgba()); // [1, 0, 0, 1]
507
508
const brightRed = color.brighten(0.2);
509
const darkRed = color.darken(0.3);
510
const grayRed = color.desaturate(0.5);
511
512
// Multiple color formats
513
const colors = [
514
new Color(0xff0000), // Number
515
new Color('#00ff00'), // Hex string
516
new Color('blue'), // Named color
517
new Color([255, 255, 0]), // RGB array
518
new Color({ r: 255, g: 0, b: 255, a: 0.5 }) // RGBA object
519
];
520
521
// Unique ID generation
522
const id1 = uid(); // Unique number
523
const id2 = uid(); // Different unique number
524
525
// Object pooling for performance
526
class Particle {
527
x = 0;
528
y = 0;
529
reset() {
530
this.x = 0;
531
this.y = 0;
532
}
533
}
534
535
const particlePool = new Pool(Particle, (particle) => particle.reset());
536
537
// Use particles
538
const particle1 = particlePool.get();
539
particle1.x = 100;
540
particle1.y = 200;
541
542
// Return to pool when done
543
particlePool.return(particle1);
544
545
// Transform utilities
546
const transform = new Transform();
547
transform.position.set(100, 100);
548
transform.scale.set(2, 2);
549
transform.rotation = Math.PI / 4;
550
transform.updateLocalTransform();
551
552
// Apply transform to sprite
553
const sprite = new Sprite(texture);
554
sprite.transform = transform;
555
556
// Debugging and logging
557
if (process.env.NODE_ENV === 'development') {
558
warn('This is a warning message');
559
logScene(app.stage);
560
}
561
562
// Network utilities
563
const imageUrl = 'images/sprite@2x.png';
564
const resolution = getResolutionOfUrl(imageUrl); // Returns 2
565
566
// Feature detection with fallbacks
567
async function initializeRenderer() {
568
if (await isWebGPUSupported()) {
569
return new WebGPURenderer();
570
} else if (isWebGLSupported()) {
571
return new WebGLRenderer();
572
} else {
573
throw new Error('No supported renderer available');
574
}
575
}
576
577
// Color themes
578
const theme = {
579
primary: new Color('#3498db'),
580
secondary: new Color('#2ecc71'),
581
danger: new Color('#e74c3c'),
582
warning: new Color('#f39c12')
583
};
584
585
// Dynamic color adjustments
586
function adjustThemeForTime(hour: number) {
587
const brightness = hour < 6 || hour > 18 ? 0.3 : 0; // Darker at night
588
589
return {
590
primary: theme.primary.darken(brightness),
591
secondary: theme.secondary.darken(brightness),
592
danger: theme.danger.darken(brightness),
593
warning: theme.warning.darken(brightness)
594
};
595
}
596
```