Loading...
Loading...
Use this skill when loading assets in Phaser 4. Covers the Loader plugin, loading images, spritesheets, atlases, audio, JSON, tilemaps, bitmap fonts, and tracking load progress. Triggers on: preload, this.load, asset loading, spritesheet, atlas, load progress.
npx skill4agent add phaserjs/phaser loading-assetsThe Phaser Loader () handles fetching all external content: images, audio, JSON, tilemaps, atlases, fonts, scripts, and more. Assets are queued inthis.load, loaded in parallel, and placed into global caches accessible by every Scene.preload()
src/loader/LoaderPlugin.jssrc/loader/File.jssrc/loader/filetypes/src/loader/events/class GameScene extends Phaser.Scene {
preload() {
this.load.image('logo', 'assets/logo.png');
}
create() {
this.add.image(400, 300, 'logo');
}
}preload()create()preload()preload()create()preload() {
// Queue files - they don't load immediately
this.load.image('sky', 'assets/sky.png');
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
this.load.audio('jump', 'assets/jump.mp3');
}
create() {
// All assets above are now available
this.add.image(400, 300, 'sky');
this.add.sprite(100, 450, 'dude');
this.sound.play('jump');
}this.loadpreload()create()create() {
this.load.image('extra', 'assets/extra.png');
this.load.once('complete', () => {
this.add.image(400, 300, 'extra');
});
this.load.start();
}baseURL + path + filenamepreload() {
// Set base URL (prepended to all relative paths)
this.load.setBaseURL('https://cdn.example.com/');
// Set path (prepended after baseURL, before filename)
this.load.setPath('assets/images/');
// Set key prefix (prepended to the cache key, not the URL)
this.load.setPrefix('LEVEL1.');
// Loads from: https://cdn.example.com/assets/images/hero.png
// Cached with key: LEVEL1.hero
this.load.image('hero', 'hero.png');
// Absolute URLs bypass the path/baseURL
this.load.image('cloud', 'https://other-server.com/cloud.png');
}const config = {
loader: {
baseURL: 'https://cdn.example.com/',
path: 'assets/',
prefix: '',
maxParallelDownloads: 32,
crossOrigin: 'anonymous',
responseType: '',
async: true,
timeout: 0,
maxRetries: 2,
imageLoadType: 'XHR' // or 'HTMLImageElement'
}
};game.texturesgame.cachegame.cache.jsongame.cache.audiogame.cache.xmlpreload() {
this.load.on('progress', (value) => {
// value is 0 to 1
console.log(`Loading: ${Math.round(value * 100)}%`);
});
this.load.on('complete', () => {
console.log('All assets loaded');
});
this.load.on('loaderror', (file) => {
console.warn('Failed to load:', file.key);
});
this.load.image('bg', 'assets/bg.png');
}preload() {
// Single image
this.load.image('star', 'assets/star.png');
// Image with normal map (pass URL array: [texture, normalMap])
this.load.image('brick', ['assets/brick.png', 'assets/brick_n.png']);
// Sprite sheet (fixed frame sizes)
this.load.spritesheet('explosion', 'assets/explosion.png', {
frameWidth: 64,
frameHeight: 64,
startFrame: 0,
endFrame: 23,
margin: 0,
spacing: 0
});
// SVG (optionally rasterize at a specific size)
this.load.svg('logo', 'assets/logo.svg', { width: 400, height: 400 });
}preload() {
// Single file
this.load.audio('bgm', 'assets/music.mp3');
// Multiple formats for cross-browser support
this.load.audio('bgm', ['assets/music.ogg', 'assets/music.mp3']);
// Audio sprite (JSON defines named regions within a single audio file)
this.load.audioSprite('sfx', 'assets/sfx.json', [
'assets/sfx.ogg',
'assets/sfx.mp3'
]);
}preload() {
// JSON data (stored in this.cache.json)
this.load.json('levelData', 'assets/level1.json');
// JSON with a dataKey to extract a sub-object
this.load.json('enemies', 'assets/data.json', 'enemies');
// Tiled tilemap (JSON format exported from Tiled)
this.load.tilemapTiledJSON('map', 'assets/map.json');
// CSV tilemap
this.load.tilemapCSV('csvmap', 'assets/level.csv');
// Impact tilemap
this.load.tilemapImpact('impactmap', 'assets/level.js');
}
create() {
const data = this.cache.json.get('levelData');
const map = this.make.tilemap({ key: 'map' });
}preload() {
// JSON atlas (e.g., TexturePacker JSON Hash/Array)
this.load.atlas('sprites', 'assets/sprites.png', 'assets/sprites.json');
// XML atlas (e.g., Starling/Sparrow format)
this.load.atlasXML('ui', 'assets/ui.png', 'assets/ui.xml');
// Multi-atlas (atlas split across multiple textures)
this.load.multiatlas('world', 'assets/world.json', 'assets/');
// Unity texture atlas format
this.load.unityAtlas('chars', 'assets/chars.png', 'assets/chars.txt');
// Aseprite atlas
this.load.aseprite('knight', 'assets/knight.png', 'assets/knight.json');
}
create() {
this.add.sprite(400, 300, 'sprites', 'walk_01');
}preload() {
// Requires both a texture and XML/JSON font data file
this.load.bitmapFont('pixels', 'assets/font.png', 'assets/font.xml');
}
create() {
this.add.bitmapText(100, 100, 'pixels', 'Hello World', 32);
}preload() {
// Load a video file. Third arg: noAudio flag (default false)
this.load.video('intro', 'assets/intro.mp4');
// Load without audio track
this.load.video('bg_loop', 'assets/loop.mp4', true);
}preload() {
// Load a font file (ttf, otf, woff, woff2)
this.load.font('myFont', 'assets/myfont.ttf', 'truetype');
// With optional font face descriptors
this.load.font('boldFont', 'assets/bold.woff2', 'woff2', {
weight: 'bold',
style: 'normal'
});
}preload() {
this.load.pack('pack1', 'assets/pack.json');
}{
"section1": {
"baseURL": "assets/",
"files": [
{ "type": "image", "key": "bg", "url": "bg.png" },
{ "type": "atlas", "key": "chars", "textureURL": "chars.png", "atlasURL": "chars.json" }
]
}
}preload() {
const progressBar = this.add.graphics();
const progressBox = this.add.graphics();
progressBox.fillStyle(0x222222, 0.8);
progressBox.fillRect(240, 270, 320, 50);
this.load.on('progress', (value) => {
progressBar.clear();
progressBar.fillStyle(0xffffff, 1);
progressBar.fillRect(250, 280, 300 * value, 30);
});
this.load.on('complete', () => {
progressBar.destroy();
progressBox.destroy();
});
// Queue your assets
this.load.image('sky', 'assets/sky.png');
// ... more assets
}this.loadreferences/REFERENCE.mdimagespritesheetatlasatlasXMLmultiatlasunityAtlasasepritesvghtmlTexturetextureaudioaudioSpritevideojsonxmltextbinaryhtmlcssglslbitmapFontfonttilemapTiledJSONtilemapCSVtilemapImpactanimationpackscriptscriptspluginscenePluginsceneFilethis.load| Event String | Callback Signature | Description |
|---|---|---|
| | A file was added to the load queue |
| | Loader has started. Progress is zero |
| | A single file finished loading (before processing/caching) |
| | Per-file download progress (0-1). Only fires if browser provides |
| | Overall load progress updated (0-1) |
| | All files loaded and processed, before internal cleanup |
| | Any file finished loading and processing |
| | Specific file finished (e.g., |
| | A file failed to load |
| | All files in the queue are done |
'start''fileprogress''load''filecomplete-{type}-{key}''filecomplete''progress''postprocess''complete'spritesheet()atlas()this.load.start()create()this.load.start()/this.load.setPath()this.load.pathbaseURLpathprefixthis.load.setPrefix('MENU.')'bg''MENU.bg'maxRetriesthis.load.maxRetriesimageLoadType: 'HTMLImageElement'<img>file://capacitor://localSchemescrossOrigin: 'anonymous'this.load.setCORS('anonymous')'Player''player''player''player'this.load.image('bg', ...)'bg'update()update()preupdatepostupdaterenderfilecompletepreload()packclass BootScene extends Phaser.Scene {
constructor() {
super({
key: 'BootScene',
pack: {
files: [
{ type: 'image', key: 'bar', url: 'loaderBar.png' }
]
}
});
}
// 'bar' is already available in preload()
}preload() {
this.load.json('level1', 'level1.json');
this.load.on('filecomplete-json-level1', (key, type, data) => {
this.load.image(data.images);
this.load.spritesheet(data.spritesheets);
});
}preload() {
this.load.pack('manifest', {
section1: {
prefix: '',
path: 'assets/',
defaultType: 'image',
files: [
{ type: 'image', key: 'bg', url: 'bg.png' },
{ type: 'spritesheet', key: 'player', url: 'player.png', frameConfig: { frameWidth: 32, frameHeight: 32 } }
]
}
});
}this.texturesthis.cache// Access cached data
const json = this.cache.json.get('levelData');
const text = this.cache.text.get('dialogue');
// Check existence
this.cache.json.exists('levelData'); // or .has('levelData')
this.textures.exists('hero');
// Remove assets to free memory
this.textures.remove('hero');
this.cache.audio.remove('bgm');
// Listen for cross-scene texture additions
this.textures.on('addtexture-mapKey', (texture) => {
// Another scene loaded 'mapKey' — now available here
});this.cache.textthis.cache.jsonthis.cache.audiothis.cache.binarythis.cache.shaderthis.cache.xmlreferences/REFERENCE.mdreferences/REFERENCE.mdsrc/loader/LoaderPlugin.jssrc/loader/File.jssrc/loader/filetypes/src/loader/events/