0
# Sprites & Textures
1
2
Textured display objects and texture management system for efficient rendering of images and sprite sheets. Sprites are the most common way to display images in PixiJS.
3
4
## Capabilities
5
6
### Sprite Class
7
8
The main class for displaying textured objects.
9
10
```typescript { .api }
11
/**
12
* Sprite represents a textured object in the scene graph
13
*/
14
class Sprite extends Container {
15
/** The texture being displayed */
16
texture: Texture;
17
/** Anchor point for positioning (0-1 range) */
18
anchor: ObservablePoint;
19
/** Color tint as hex number */
20
tint: number;
21
/** Blend mode for rendering */
22
blendMode: BLEND_MODES;
23
/** Shader for custom rendering */
24
shader: Shader | Filter;
25
/** Plugin name for custom rendering */
26
pluginName: string;
27
/** Whether to round pixel positions */
28
roundPixels: boolean;
29
30
/**
31
* Create sprite from texture source
32
* @param source - Texture source (URL, Texture, etc.)
33
* @param skipCache - Skip texture cache
34
*/
35
static from(source: TextureSource, skipCache?: boolean): Sprite;
36
37
/**
38
* Create a new Sprite
39
* @param texture - Texture to display
40
*/
41
constructor(texture?: Texture);
42
43
/** Get sprite width */
44
get width(): number;
45
set width(value: number);
46
47
/** Get sprite height */
48
get height(): number;
49
set height(value: number);
50
51
/**
52
* Calculate sprite bounds
53
* @param skipUpdate - Skip transform update
54
* @param rect - Rectangle to store result
55
*/
56
getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle;
57
58
/**
59
* Test if point is inside sprite
60
* @param point - Point to test
61
*/
62
containsPoint(point: IPointData): boolean;
63
64
/** Destroy sprite and optionally its texture */
65
destroy(options?: boolean | IDestroyOptions): void;
66
}
67
68
interface IDestroyOptions {
69
/** Destroy children */
70
children?: boolean;
71
/** Destroy texture */
72
texture?: boolean;
73
/** Destroy base texture */
74
baseTexture?: boolean;
75
}
76
```
77
78
### Texture Class
79
80
The core texture class representing GPU texture resources.
81
82
```typescript { .api }
83
/**
84
* Texture represents a GPU texture resource
85
*/
86
class Texture extends EventEmitter {
87
/** Base texture resource */
88
baseTexture: BaseTexture;
89
/** Frame rectangle within the base texture */
90
frame: Rectangle;
91
/** Rotation (0, 2, 4, 6, 8, 10, 12, 14) */
92
rotate: number;
93
/** Texture width */
94
readonly width: number;
95
/** Texture height */
96
readonly height: number;
97
/** Whether texture is valid */
98
valid: boolean;
99
/** Whether texture requires update */
100
requiresUpdate: boolean;
101
/** Original frame */
102
orig: Rectangle;
103
/** Trim rectangle */
104
trim: Rectangle;
105
/** Default anchor */
106
defaultAnchor: Point;
107
/** UV transform matrix */
108
uvMatrix: TextureMatrix;
109
/** No frame constant */
110
static readonly EMPTY: Texture;
111
/** White 1x1 texture */
112
static readonly WHITE: Texture;
113
114
/**
115
* Create texture from source
116
* @param source - Source (URL, HTMLImageElement, etc.)
117
* @param options - Base texture options
118
* @param strict - Strict mode
119
*/
120
static from(source: TextureSource, options?: IBaseTextureOptions, strict?: boolean): Texture;
121
122
/**
123
* Create texture from URL
124
* @param url - Image URL
125
* @param options - Base texture options
126
*/
127
static fromURL(url: string, options?: IBaseTextureOptions): Promise<Texture>;
128
129
/**
130
* Create texture from buffer
131
* @param buffer - Pixel buffer
132
* @param width - Width in pixels
133
* @param height - Height in pixels
134
* @param options - Base texture options
135
*/
136
static fromBuffer(buffer: Float32Array | Uint8Array, width: number, height: number, options?: IBaseTextureOptions): Texture;
137
138
/**
139
* Create texture from canvas
140
* @param canvas - Canvas element
141
* @param scaleMode - Scale mode
142
* @param origin - Origin identifier
143
*/
144
static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: SCALE_MODES, origin?: string): Texture;
145
146
/**
147
* Create a new Texture
148
* @param baseTexture - Base texture
149
* @param frame - Frame rectangle
150
* @param orig - Original rectangle
151
* @param trim - Trim rectangle
152
* @param rotate - Rotation
153
* @param anchor - Default anchor
154
*/
155
constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number, anchor?: IPointData);
156
157
/** Update texture */
158
update(): void;
159
160
/**
161
* Update UV mapping
162
* @param frame - New frame
163
*/
164
updateUvs(): void;
165
166
/** Clone the texture */
167
clone(): Texture;
168
169
/**
170
* Destroy texture
171
* @param destroyBase - Also destroy base texture
172
*/
173
destroy(destroyBase?: boolean): void;
174
175
/** Cast to base texture */
176
castToBaseTexture(): BaseTexture;
177
}
178
179
type TextureSource = string | number | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap;
180
```
181
182
### BaseTexture Class
183
184
The base texture resource that manages the actual image data.
185
186
```typescript { .api }
187
/**
188
* BaseTexture manages the actual image resource
189
*/
190
class BaseTexture extends EventEmitter {
191
/** Image resource */
192
resource: Resource;
193
/** Texture width */
194
width: number;
195
/** Texture height */
196
height: number;
197
/** Device pixel ratio */
198
resolution: number;
199
/** Mipmap mode */
200
mipmap: MIPMAP_MODES;
201
/** Wrap mode for U coordinate */
202
wrapMode: WRAP_MODES;
203
/** Scale mode */
204
scaleMode: SCALE_MODES;
205
/** Pixel format */
206
format: FORMATS;
207
/** Data type */
208
type: TYPES;
209
/** WebGL target */
210
target: TARGETS;
211
/** Alpha mode */
212
alphaMode: ALPHA_MODES;
213
/** Anisotropic filtering level */
214
anisotropicLevel: number;
215
/** Whether texture is valid */
216
valid: boolean;
217
/** Whether texture is loading */
218
isLoading: boolean;
219
/** Whether texture has been destroyed */
220
destroyed: boolean;
221
/** Texture cache ID */
222
textureCacheIds: string[];
223
/** Whether to round pixels */
224
roundPixels: boolean;
225
/** Whether texture is ready */
226
ready: boolean;
227
228
/**
229
* Create base texture from source
230
* @param source - Image source
231
* @param options - Creation options
232
* @param strict - Strict mode
233
*/
234
static from(source: ImageSource, options?: IBaseTextureOptions, strict?: boolean): BaseTexture;
235
236
/**
237
* Create a new BaseTexture
238
* @param resource - Resource or source
239
* @param options - Creation options
240
*/
241
constructor(resource?: Resource | ImageSource, options?: IBaseTextureOptions);
242
243
/**
244
* Set resource
245
* @param resource - New resource
246
*/
247
setResource(resource: Resource): this;
248
249
/**
250
* Set size
251
* @param desiredWidth - New width
252
* @param desiredHeight - New height
253
* @param resolution - New resolution
254
*/
255
setSize(desiredWidth: number, desiredHeight?: number, resolution?: number): this;
256
257
/**
258
* Set style
259
* @param scaleMode - Scale mode
260
* @param mipmap - Mipmap mode
261
*/
262
setStyle(scaleMode?: SCALE_MODES, mipmap?: MIPMAP_MODES): this;
263
264
/**
265
* Set real size
266
* @param realWidth - Real width
267
* @param realHeight - Real height
268
* @param resolution - Resolution
269
*/
270
setRealSize(realWidth: number, realHeight: number, resolution?: number): this;
271
272
/** Update texture */
273
update(): void;
274
275
/** Destroy base texture */
276
destroy(): void;
277
278
/** Dispose WebGL resources */
279
dispose(): void;
280
}
281
282
interface IBaseTextureOptions {
283
scaleMode?: SCALE_MODES;
284
resolution?: number;
285
mipmap?: MIPMAP_MODES;
286
anisotropicLevel?: number;
287
wrapMode?: WRAP_MODES;
288
format?: FORMATS;
289
type?: TYPES;
290
target?: TARGETS;
291
alphaMode?: ALPHA_MODES;
292
width?: number;
293
height?: number;
294
resourceOptions?: any;
295
}
296
297
type ImageSource = HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap | string;
298
```
299
300
### Texture Resources
301
302
Different resource types for various texture sources.
303
304
```typescript { .api }
305
/**
306
* Base resource class
307
*/
308
abstract class Resource {
309
/** Resource width */
310
width: number;
311
/** Resource height */
312
height: number;
313
/** Whether resource is valid */
314
valid: boolean;
315
/** Whether resource is destroyed */
316
destroyed: boolean;
317
318
constructor(width?: number, height?: number);
319
320
/** Update resource */
321
update(): void;
322
323
/** Load resource */
324
load(): Promise<Resource>;
325
326
/** Get resource style */
327
style(renderer: Renderer, baseTexture: BaseTexture, glTexture: GLTexture): boolean;
328
329
/** Dispose resource */
330
dispose(): void;
331
332
/** Destroy resource */
333
destroy(): void;
334
}
335
336
/**
337
* Image-based texture resource
338
*/
339
class ImageResource extends Resource {
340
/** Source image element */
341
source: HTMLImageElement;
342
/** Image URL */
343
url: string;
344
/** Whether to create bitmap */
345
createBitmap: boolean;
346
/** Cross-origin setting */
347
crossorigin: boolean | string;
348
/** Alpha mode */
349
alphaMode: ALPHA_MODES;
350
351
constructor(source: HTMLImageElement | string, options?: IImageResourceOptions);
352
353
/** Load image */
354
load(createBitmap?: boolean): Promise<ImageResource>;
355
}
356
357
interface IImageResourceOptions {
358
crossorigin?: boolean | string;
359
autoLoad?: boolean;
360
createBitmap?: boolean;
361
alphaMode?: ALPHA_MODES;
362
}
363
364
/**
365
* Canvas-based texture resource
366
*/
367
class CanvasResource extends Resource {
368
/** Source canvas element */
369
source: HTMLCanvasElement;
370
371
constructor(source: HTMLCanvasElement);
372
373
/** Update canvas resource */
374
update(): void;
375
}
376
377
/**
378
* Video-based texture resource
379
*/
380
class VideoResource extends Resource {
381
/** Source video element */
382
source: HTMLVideoElement;
383
/** Whether to auto-update */
384
autoUpdate: boolean;
385
/** Update FPS */
386
updateFPS: number;
387
388
constructor(source: HTMLVideoElement | string | string[], options?: IVideoResourceOptions);
389
390
/** Update video frame */
391
update(deltaTime?: number): void;
392
393
/** Load video */
394
load(): Promise<VideoResource>;
395
}
396
397
interface IVideoResourceOptions {
398
autoLoad?: boolean;
399
autoPlay?: boolean;
400
updateFPS?: number;
401
crossorigin?: boolean | string;
402
}
403
```
404
405
**Usage Examples:**
406
407
```typescript
408
import { Sprite, Texture, BaseTexture, Assets } from "pixi.js";
409
410
// Create sprite from URL
411
const sprite1 = Sprite.from('https://example.com/image.png');
412
413
// Create sprite from loaded texture
414
const texture = await Assets.load('player.png');
415
const sprite2 = new Sprite(texture);
416
417
// Configure sprite properties
418
sprite2.anchor.set(0.5); // Center anchor
419
sprite2.tint = 0xff0000; // Red tint
420
sprite2.blendMode = BLEND_MODES.ADD; // Additive blending
421
sprite2.width = 100; // Scale to 100px width
422
sprite2.height = 150; // Scale to 150px height
423
424
// Working with texture frames (sprite sheets)
425
const baseTexture = await Assets.load('spritesheet.png');
426
const frame1 = new Texture(baseTexture, new Rectangle(0, 0, 32, 32));
427
const frame2 = new Texture(baseTexture, new Rectangle(32, 0, 32, 32));
428
429
// Create sprites from frames
430
const sprite3 = new Sprite(frame1);
431
const sprite4 = new Sprite(frame2);
432
433
// Dynamic texture creation
434
const canvas = document.createElement('canvas');
435
canvas.width = 100;
436
canvas.height = 100;
437
const ctx = canvas.getContext('2d');
438
ctx.fillStyle = 'red';
439
ctx.fillRect(0, 0, 100, 100);
440
441
const dynamicTexture = Texture.from(canvas);
442
const dynamicSprite = new Sprite(dynamicTexture);
443
444
// Video texture
445
const video = document.createElement('video');
446
video.src = 'movie.mp4';
447
video.loop = true;
448
video.play();
449
450
const videoTexture = Texture.from(video);
451
const videoSprite = new Sprite(videoTexture);
452
```
453
454
### RenderTexture
455
456
Textures that can be rendered to for advanced effects.
457
458
```typescript { .api }
459
/**
460
* Texture that can be rendered to
461
*/
462
class RenderTexture extends Texture {
463
/** Base render texture */
464
baseRenderTexture: BaseRenderTexture;
465
466
/**
467
* Create a new RenderTexture
468
* @param baseRenderTexture - Base render texture
469
* @param frame - Frame rectangle
470
*/
471
constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle);
472
473
/**
474
* Create render texture
475
* @param options - Creation options
476
*/
477
static create(options?: IBaseTextureOptions): RenderTexture;
478
479
/**
480
* Resize render texture
481
* @param desiredWidth - New width
482
* @param desiredHeight - New height
483
* @param resizeBaseTexture - Resize base texture too
484
*/
485
resize(desiredWidth: number, desiredHeight: number, resizeBaseTexture?: boolean): void;
486
487
/**
488
* Set frame
489
* @param frame - New frame
490
*/
491
setFrame(frame: Rectangle): void;
492
}
493
494
/**
495
* Base render texture for render-to-texture operations
496
*/
497
class BaseRenderTexture extends BaseTexture {
498
/** Clear color */
499
clearColor: number[];
500
/** Framebuffer */
501
framebuffer: Framebuffer;
502
/** Multisample level */
503
multisample: MSAA_QUALITY;
504
505
constructor(options?: IBaseRenderTextureOptions);
506
507
/**
508
* Resize base render texture
509
* @param desiredWidth - New width
510
* @param desiredHeight - New height
511
*/
512
resize(desiredWidth: number, desiredHeight: number): void;
513
514
/** Dispose framebuffer */
515
dispose(): void;
516
517
/** Destroy base render texture */
518
destroy(): void;
519
}
520
521
interface IBaseRenderTextureOptions extends IBaseTextureOptions {
522
clearColor?: number[];
523
multisample?: MSAA_QUALITY;
524
}
525
```
526
527
**Render Texture Examples:**
528
529
```typescript
530
import { RenderTexture, Sprite, Graphics, Application } from "pixi.js";
531
532
// Create render texture
533
const renderTexture = RenderTexture.create({ width: 256, height: 256 });
534
535
// Create graphics to render
536
const graphics = new Graphics();
537
graphics.beginFill(0xff0000);
538
graphics.drawCircle(128, 128, 64);
539
graphics.endFill();
540
541
// Render to texture
542
app.renderer.render(graphics, { renderTexture });
543
544
// Use render texture as sprite texture
545
const sprite = new Sprite(renderTexture);
546
app.stage.addChild(sprite);
547
548
// Dynamic render texture updates (requires TickerPlugin)
549
// app.ticker.add(() => {
550
// graphics.rotation += 0.01;
551
// app.renderer.render(graphics, { renderTexture, clear: true });
552
// });
553
```
554
555
### Texture Cache
556
557
Global texture caching system for performance optimization.
558
559
```typescript { .api }
560
/**
561
* Global texture cache utilities
562
*/
563
class TextureCache {
564
/**
565
* Add texture to cache
566
* @param texture - Texture to cache
567
* @param id - Cache ID
568
*/
569
static add(texture: Texture, id: string): void;
570
571
/**
572
* Remove texture from cache
573
* @param id - Cache ID
574
*/
575
static remove(id: string): Texture | null;
576
577
/**
578
* Get texture from cache
579
* @param id - Cache ID
580
*/
581
static get(id: string): Texture | undefined;
582
583
/** Clear all cached textures */
584
static clear(): void;
585
586
/** Get all cache keys */
587
static getKeys(): string[];
588
589
/** Check if texture is cached */
590
static has(id: string): boolean;
591
}
592
```
593
594
## Performance Optimization
595
596
```typescript
597
// Texture atlasing - combine multiple images into one texture
598
const atlas = await Assets.load('game-atlas.json'); // TexturePacker format
599
const playerTexture = atlas['player.png'];
600
const enemyTexture = atlas['enemy.png'];
601
602
// Proper texture disposal
603
const textures = [];
604
for (let i = 0; i < 100; i++) {
605
textures.push(Texture.from(`frame${i}.png`));
606
}
607
608
// Later, clean up
609
textures.forEach(texture => texture.destroy(true));
610
611
// Use appropriate scale modes
612
const pixelArtTexture = Texture.from('pixel-art.png');
613
pixelArtTexture.baseTexture.scaleMode = SCALE_MODES.NEAREST; // Sharp pixels
614
615
const photoTexture = Texture.from('photo.jpg');
616
photoTexture.baseTexture.scaleMode = SCALE_MODES.LINEAR; // Smooth scaling
617
618
// Batch sprite creation
619
const sprites = [];
620
const texture = Texture.from('particle.png');
621
for (let i = 0; i < 1000; i++) {
622
sprites.push(new Sprite(texture)); // Reuse same texture
623
}
624
```