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

assets.mddocs/

0

# Asset Loading

1

2

PixiJS provides a comprehensive, modern asset loading system designed for high-performance web applications. The Assets system offers a promise-based API with intelligent caching, format detection, bundle management, and background loading capabilities.

3

4

## Overview

5

6

The Assets system is built around four core responsibilities:

7

1. **Resolution**: Map URLs to keys and resolve them according to browser capabilities

8

2. **Loading**: Load resources and transform them into usable assets

9

3. **Caching**: Store assets and provide efficient access mechanisms

10

4. **Management**: Handle asset lifecycle including unloading and cleanup

11

12

### Key Features

13

14

- Promise-based API with automatic deduplication

15

- Intelligent format detection (AVIF, WebP fallbacks)

16

- Bundle management for organized asset groups

17

- Background loading for improved UX

18

- Worker-based image processing when available

19

- Comprehensive manifest support

20

- Texture atlas and spritesheet support

21

22

## Core Classes

23

24

### Assets Class { .api }

25

26

The main entry point for all asset operations. This is a singleton class accessed via `Assets`.

27

28

```typescript

29

class AssetsClass {

30

// Core components

31

resolver: Resolver;

32

loader: Loader;

33

cache: typeof Cache;

34

35

// Initialization

36

init(options?: AssetInitOptions): Promise<void>;

37

38

// Asset loading

39

load<T>(urls: string | UnresolvedAsset, onProgress?: ProgressCallback): Promise<T>;

40

load<T>(urls: string[] | UnresolvedAsset[], onProgress?: ProgressCallback): Promise<Record<string, T>>;

41

42

// Asset management

43

add(data: ArrayOr<UnresolvedAsset>): void;

44

add(aliases: ArrayOr<string>, srcs?: AssetSrc, data?: unknown, format?: string, loadParser?: LoadParserName): void;

45

46

// Bundle operations

47

addBundle(bundleId: string, assets: AssetsBundle['assets']): void;

48

loadBundle(bundleIds: ArrayOr<string>, onProgress?: ProgressCallback): Promise<any>;

49

50

// Background loading

51

backgroundLoad(urls: ArrayOr<string>): Promise<void>;

52

backgroundLoadBundle(bundleIds: ArrayOr<string>): Promise<void>;

53

54

// Cache access

55

get<T>(keys: string): T;

56

get<T>(keys: string[]): Record<string, T>;

57

58

// Asset cleanup

59

unload(urls: ArrayOr<string> | ResolvedAsset | ResolvedAsset[]): Promise<void>;

60

unloadBundle(bundleIds: ArrayOr<string>): Promise<void>;

61

62

// Configuration

63

setPreferences(preferences: Partial<AssetsPreferences>): void;

64

reset(): void;

65

}

66

```

67

68

### Cache Interface { .api }

69

70

Global cache for all loaded assets with parser-based extensibility.

71

72

```typescript

73

class CacheClass {

74

// Cache operations

75

has(key: string): boolean;

76

get<T>(key: string): T;

77

set(key: string | string[], value: unknown): void;

78

remove(key: string): void;

79

80

// Management

81

reset(): void;

82

83

// Extensibility

84

readonly parsers: CacheParser[];

85

}

86

```

87

88

### Resolver Interface { .api }

89

90

Maps asset keys to URLs and handles format/resolution preferences.

91

92

```typescript

93

class Resolver {

94

// Configuration

95

basePath: string;

96

rootPath: string;

97

readonly parsers: ResolveURLParser[];

98

99

// Preferences

100

prefer(...preferOrders: PreferOrder[]): void;

101

setBundleIdentifier(bundleIdentifier: BundleIdentifierOptions): void;

102

setDefaultSearchParams(searchParams: string | Record<string, unknown>): void;

103

104

// Asset registration

105

add(data: ArrayOr<UnresolvedAsset>): void;

106

addManifest(manifest: AssetsManifest): void;

107

addBundle(bundleId: string, assets: AssetsBundle['assets']): void;

108

109

// Resolution

110

resolve(keys: string): ResolvedAsset;

111

resolve(keys: string[]): Record<string, ResolvedAsset>;

112

resolveUrl(key: ArrayOr<string>): string | Record<string, string>;

113

resolveBundle(bundleIds: ArrayOr<string>): Record<string, ResolvedAsset> | Record<string, Record<string, ResolvedAsset>>;

114

115

// Utilities

116

hasKey(key: string): boolean;

117

hasBundle(key: string): boolean;

118

getAlias(asset: UnresolvedAsset): string[];

119

120

// Management

121

reset(): void;

122

}

123

```

124

125

### Loader Interface { .api }

126

127

Handles the actual loading and parsing of assets.

128

129

```typescript

130

class Loader {

131

// Parsers management

132

readonly parsers: LoaderParser[];

133

readonly promiseCache: Record<string, PromiseAndParser>;

134

135

// Loading operations

136

load<T>(assetsToLoad: ResolvedAsset | ResolvedAsset[], onProgress?: ProgressCallback): Promise<T | Record<string, T>>;

137

138

// Unloading

139

unload(assetsToUnload: ResolvedAsset | ResolvedAsset[]): Promise<void>;

140

141

// Management

142

reset(): void;

143

}

144

```

145

146

### Texture Class Essentials { .api }

147

148

Core texture functionality used by the assets system.

149

150

```typescript

151

class Texture<R extends Resource = Resource> extends EventEmitter {

152

// Core properties

153

baseTexture: BaseTexture<R>;

154

frame: Rectangle;

155

orig: Rectangle;

156

trim: Rectangle;

157

valid: boolean;

158

destroyed: boolean;

159

160

// Texture creation

161

static from(source: TextureSource, options?: IBaseTextureOptions, strict?: boolean): Texture;

162

static fromURL(url: string, options?: IBaseTextureOptions): Promise<Texture>;

163

static fromBuffer(buffer: BufferType, width: number, height: number, options?: IBaseTextureOptions): Texture;

164

165

// Cache management

166

static addToCache(texture: Texture, id: string): void;

167

static removeFromCache(id: string): Texture | null;

168

169

// Lifecycle

170

clone(): Texture;

171

update(): void;

172

destroy(destroyBase?: boolean): void;

173

}

174

```

175

176

### Spritesheet Class { .api }

177

178

Manages texture atlases and sprite animations.

179

180

```typescript

181

class Spritesheet<S extends ISpritesheetData = ISpritesheetData> {

182

// Static configuration

183

static readonly BATCH_SIZE: number;

184

185

// Core properties

186

baseTexture: BaseTexture;

187

textures: Record<keyof S['frames'], Texture>;

188

animations: Record<keyof NonNullable<S['animations']>, Texture[]>;

189

data: S;

190

resolution: number;

191

linkedSheets: Spritesheet<S>[];

192

cachePrefix: string;

193

194

// Constructor

195

constructor(options: SpritesheetOptions<S>);

196

constructor(texture: BaseTexture | Texture, data: S, resolutionFilename?: string);

197

198

// Processing

199

parse(): Promise<utils.Dict<Texture>>;

200

201

// Lifecycle

202

destroy(destroyBase?: boolean): void;

203

}

204

```

205

206

## Type Definitions

207

208

### Core Asset Types

209

210

```typescript

211

// Basic types

212

type ArrayOr<T> = T | T[];

213

type LoadParserName = 'loadJson' | 'loadSVG' | 'loadTextures' | 'loadTxt' | 'loadVideo' | 'loadWebFont' | string;

214

215

// Asset definitions

216

interface ResolvedAsset<T = any> {

217

alias?: string[];

218

src?: string;

219

data?: T;

220

format?: string;

221

loadParser?: LoadParserName;

222

[key: string]: any;

223

}

224

225

interface UnresolvedAsset<T = any> extends Omit<ResolvedAsset<T>, 'src' | 'srcs' | 'name' | 'alias'> {

226

alias?: ArrayOr<string>;

227

src?: AssetSrc;

228

}

229

230

type AssetSrc = ArrayOr<string> | ArrayOr<ResolvedSrc>;

231

type ResolvedSrc = Pick<ResolvedAsset, 'src' | 'format' | 'loadParser' | 'data'> & { [key: string]: any };

232

```

233

234

### Bundle and Manifest Types

235

236

```typescript

237

interface AssetsBundle {

238

name: string;

239

assets: UnresolvedAsset[] | Record<string, ArrayOr<string> | UnresolvedAssetObject>;

240

}

241

242

interface AssetsManifest {

243

bundles: AssetsBundle[];

244

}

245

246

type UnresolvedAssetObject = Omit<UnresolvedAsset, 'name' | 'alias'>;

247

```

248

249

### Configuration Types

250

251

```typescript

252

interface AssetInitOptions {

253

basePath?: string;

254

defaultSearchParams?: string | Record<string, any>;

255

manifest?: string | AssetsManifest;

256

texturePreference?: {

257

resolution?: number | number[];

258

format?: ArrayOr<string>;

259

};

260

skipDetections?: boolean;

261

bundleIdentifier?: BundleIdentifierOptions;

262

preferences?: Partial<AssetsPreferences>;

263

}

264

265

interface AssetsPreferences extends LoadTextureConfig, GlobalMixins.AssetsPreferences {}

266

267

interface LoadTextureConfig {

268

preferWorkers: boolean;

269

preferCreateImageBitmap: boolean;

270

crossOrigin: HTMLImageElement['crossOrigin'];

271

}

272

273

type ProgressCallback = (progress: number) => void;

274

```

275

276

### Spritesheet Types

277

278

```typescript

279

interface ISpritesheetData {

280

animations?: utils.Dict<string[]>;

281

frames: utils.Dict<ISpritesheetFrameData>;

282

meta: {

283

app?: string;

284

format?: string;

285

image?: string;

286

scale: string | number;

287

size?: { h: number; w: number; };

288

version?: string;

289

related_multi_packs?: string[];

290

};

291

}

292

293

interface ISpritesheetFrameData {

294

frame: { x: number; y: number; w: number; h: number; };

295

trimmed?: boolean;

296

rotated?: boolean;

297

sourceSize?: { w: number; h: number; };

298

spriteSourceSize?: { x: number; y: number; w?: number; h?: number; };

299

anchor?: IPointData;

300

borders?: ITextureBorders;

301

}

302

303

interface SpritesheetOptions<S extends ISpritesheetData = ISpritesheetData> {

304

texture: BaseTexture | Texture;

305

data: S;

306

resolutionFilename?: string;

307

cachePrefix?: string;

308

}

309

```

310

311

### Resolver Types

312

313

```typescript

314

interface BundleIdentifierOptions {

315

connector?: string;

316

createBundleAssetId?: (bundleId: string, assetId: string) => string;

317

extractAssetIdFromBundle?: (bundleId: string, assetBundleId: string) => string;

318

}

319

320

interface PreferOrder {

321

priority?: string[];

322

params: Record<string, any[]>;

323

}

324

```

325

326

## Usage Examples

327

328

### Basic Asset Loading

329

330

```typescript

331

import { Assets } from 'pixi.js';

332

333

// Initialize the assets system (optional)

334

await Assets.init({

335

basePath: 'https://cdn.example.com/assets/',

336

texturePreference: {

337

resolution: [2, 1], // Prefer 2x, fallback to 1x

338

format: ['avif', 'webp', 'png'] // Format preference

339

}

340

});

341

342

// Load a single asset

343

const texture = await Assets.load('bunny.png');

344

345

// Load multiple assets

346

const assets = await Assets.load(['bunny.png', 'background.jpg']);

347

console.log(assets.bunny, assets.background);

348

349

// Load with progress tracking

350

const texture = await Assets.load('large-image.png', (progress) => {

351

console.log(`Loading: ${Math.round(progress * 100)}%`);

352

});

353

```

354

355

### Advanced Asset Registration

356

357

```typescript

358

// Register asset with alias and metadata

359

Assets.add({

360

alias: 'player-sprite',

361

src: 'characters/player.png',

362

data: {

363

scaleMode: SCALE_MODES.NEAREST,

364

resolution: 2

365

}

366

});

367

368

// Register multiple format assets

369

Assets.add({

370

alias: 'background',

371

src: ['bg.avif', 'bg.webp', 'bg.png'], // Will choose best supported format

372

});

373

374

// Register with custom parser

375

Assets.add({

376

alias: 'config',

377

src: 'config.xml',

378

loadParser: 'loadTxt' // Force specific parser

379

});

380

```

381

382

### Bundle Management

383

384

```typescript

385

// Create bundles for different game screens

386

Assets.addBundle('game-ui', {

387

'health-bar': 'ui/health.png',

388

'mana-bar': 'ui/mana.png',

389

'inventory-bg': 'ui/inventory-background.png'

390

});

391

392

Assets.addBundle('level-1', {

393

'tileset': 'levels/1/tileset.png',

394

'background': 'levels/1/bg.png',

395

'music': 'levels/1/theme.mp3'

396

});

397

398

// Load entire bundles

399

const uiAssets = await Assets.loadBundle('game-ui');

400

const levelAssets = await Assets.loadBundle('level-1');

401

402

// Load multiple bundles with progress

403

const allAssets = await Assets.loadBundle(['game-ui', 'level-1'], (progress) => {

404

console.log(`Bundle loading: ${Math.round(progress * 100)}%`);

405

});

406

```

407

408

### Manifest-Based Loading

409

410

```typescript

411

const manifest = {

412

bundles: [

413

{

414

name: 'preload',

415

assets: [

416

{

417

alias: 'logo',

418

src: 'branding/logo.{png,webp}'

419

},

420

{

421

alias: 'loading-bar',

422

src: 'ui/loading-bar.png'

423

}

424

]

425

},

426

{

427

name: 'game-assets',

428

assets: [

429

{

430

alias: 'spritesheet',

431

src: 'game/sprites.{png,webp}.json' // Spritesheet with format options

432

},

433

{

434

alias: 'sound-effects',

435

src: 'audio/sfx.json'

436

}

437

]

438

}

439

]

440

};

441

442

await Assets.init({ manifest });

443

444

// Load preload bundle first

445

const preloadAssets = await Assets.loadBundle('preload');

446

// Then load main game assets

447

const gameAssets = await Assets.loadBundle('game-assets');

448

```

449

450

### Texture Atlas and Spritesheet Usage

451

452

```typescript

453

// Load spritesheet via Assets

454

const spritesheet = await Assets.load('characters.json');

455

456

// Access individual textures

457

const idleTexture = spritesheet.textures['player-idle.png'];

458

const runTexture = spritesheet.textures['player-run-01.png'];

459

460

// Use animations if defined in spritesheet

461

const runAnimation = spritesheet.animations['player-run'];

462

const animatedSprite = new AnimatedSprite(runAnimation);

463

464

// Direct spritesheet creation

465

import { Spritesheet, BaseTexture } from 'pixi.js';

466

467

const baseTexture = await Assets.load('characters.png');

468

const spritesheetData = await Assets.load('characters.json');

469

470

const sheet = new Spritesheet(baseTexture, spritesheetData);

471

await sheet.parse();

472

473

// Access parsed textures and animations

474

const playerTexture = sheet.textures['player.png'];

475

const enemyAnimation = sheet.animations['enemy-walk'];

476

```

477

478

### Background Loading

479

480

```typescript

481

// Start loading assets in background

482

Assets.backgroundLoad([

483

'level-2-tileset.png',

484

'level-2-music.mp3',

485

'level-2-enemies.json'

486

]);

487

488

// Background load bundles

489

Assets.backgroundLoadBundle(['level-2', 'level-3']);

490

491

// Later when needed, these will resolve instantly if already loaded

492

const level2Assets = await Assets.loadBundle('level-2'); // May be instant!

493

```

494

495

### Asset Resolution and Caching

496

497

```typescript

498

// Configure resolution preferences

499

Assets.resolver.prefer({

500

params: {

501

format: ['avif', 'webp', 'png'],

502

resolution: [2, 1]

503

}

504

});

505

506

// Register assets with multiple formats and resolutions

507

Assets.add({

508

alias: 'character',

509

src: [

510

'sprites/character@2x.avif',

511

'sprites/character@2x.webp',

512

'sprites/character@2x.png',

513

'sprites/character.avif',

514

'sprites/character.webp',

515

'sprites/character.png'

516

]

517

});

518

519

// Resolver will choose best match based on preferences

520

const characterTexture = await Assets.load('character');

521

522

// Direct cache access

523

const cachedTexture = Assets.cache.get('character');

524

if (cachedTexture) {

525

// Use cached version

526

}

527

```

528

529

### Custom Loading Preferences

530

531

```typescript

532

// Configure texture loading preferences

533

Assets.setPreferences({

534

preferWorkers: true, // Use workers when available

535

preferCreateImageBitmap: true, // Use ImageBitmap API

536

crossOrigin: 'anonymous' // CORS setting for images

537

});

538

539

// These preferences affect how textures are loaded:

540

// - Workers provide better performance for large images

541

// - ImageBitmap enables efficient GPU transfer

542

// - CrossOrigin handling for external assets

543

```

544

545

### Asset Cleanup

546

547

```typescript

548

// Unload specific assets

549

await Assets.unload(['old-level-assets', 'unused-textures']);

550

551

// Unload entire bundles

552

await Assets.unloadBundle(['level-1', 'cutscenes']);

553

554

// Check before unloading

555

if (Assets.cache.has('old-asset')) {

556

await Assets.unload('old-asset');

557

}

558

559

// Reset entire assets system (development only)

560

Assets.reset();

561

```

562

563

## Advanced Features

564

565

### Custom Search Parameters

566

567

```typescript

568

// Set default search parameters for all assets

569

Assets.resolver.setDefaultSearchParams('version=1.2.0&cdn=primary');

570

571

// Or as object

572

Assets.resolver.setDefaultSearchParams({

573

version: '1.2.0',

574

cdn: 'primary',

575

format: 'optimized'

576

});

577

```

578

579

### Base Path Configuration

580

581

```typescript

582

// Set base path for all relative URLs

583

Assets.resolver.basePath = 'https://cdn.game.com/assets/';

584

585

// Set root path for absolute URLs

586

Assets.resolver.rootPath = 'https://cdn.game.com/';

587

588

Assets.add('level', '/levels/desert.png'); // Resolves to https://cdn.game.com/levels/desert.png

589

Assets.add('ui', 'interface/hud.png'); // Resolves to https://cdn.game.com/assets/interface/hud.png

590

```

591

592

### Format Detection and Browser Support

593

594

The Assets system automatically detects browser capabilities and prefers modern formats:

595

596

```typescript

597

// Automatic format detection (default behavior)

598

await Assets.init({

599

texturePreference: {

600

format: ['avif', 'webp', 'png'] // Preference order

601

},

602

skipDetections: false // Enable automatic detection

603

});

604

605

// Manual format control

606

await Assets.init({

607

skipDetections: true, // Disable detection for performance

608

texturePreference: {

609

format: ['webp', 'png'] // Only these formats

610

}

611

});

612

```

613

614

The system will automatically fall back to supported formats, ensuring compatibility across different browsers and devices.

615

616

## Performance Considerations

617

618

### Loading Optimization

619

620

1. **Use background loading** for assets needed later

621

2. **Prefer modern formats** (AVIF, WebP) with fallbacks

622

3. **Enable worker loading** for large images

623

4. **Bundle related assets** to reduce HTTP requests

624

5. **Specify resolutions** appropriate for target devices

625

626

### Memory Management

627

628

1. **Unload unused assets** to free memory

629

2. **Use appropriate texture resolutions** for device capabilities

630

3. **Destroy sprites** before unloading their textures

631

4. **Monitor cache size** in development tools

632

633

### Bundle Strategy

634

635

1. **Group by usage patterns** (UI, level-specific, shared)

636

2. **Load critical assets first** (loading screen, UI)

637

3. **Background load next level** while playing current

638

4. **Keep shared assets loaded** across levels

639

640

The PixiJS Assets system provides a robust, modern foundation for managing all types of game and application resources, with intelligent defaults and extensive customization options for advanced use cases.