Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Game Loop and Scenes

Loading Assets in Phaser: Images, Audio, JSON and Textures

Learn the Phaser Loader: preload, texture keys, load.image, spritesheet, audio, JSON and atlas, a progress bar, loading errors and drawing textures in code.

Games are made of assets: images for characters and backgrounds, sounds for effects and music, data files for levels. Phaser loads them with its Loader. The key idea is simple: you queue files in preload, Phaser downloads them, stores them under a key you choose, and only then calls create, so everything is ready.

On this site. The preview is a sandbox without our own file server for game assets, so the live examples create images in code and load tiny images embedded in the code as data: URLs. In your own project you load real files from a folder exactly as the code blocks show; the loader API is identical.

The pattern: queue in preload, use in create

JavaScript
class Boot extends Phaser.Scene {
  preload() {
    this.load.image('sky', 'assets/sky.png');             // key, url
    this.load.spritesheet('hero', 'assets/hero.png', { frameWidth: 32, frameHeight: 48 });
    this.load.audio('jump', ['assets/jump.ogg', 'assets/jump.mp3']);
    this.load.json('levels', 'assets/levels.json');
  }

  create() {
    this.add.image(400, 225, 'sky');                      // use the key
    const levels = this.cache.json.get('levels');         // data from the cache
  }
}

Each this.load.* call only adds a file to the queue; nothing downloads until preload ends. Then the loader fetches files in parallel and create runs when the last one is done. If you call a load method later (for example in create), you must start the loader yourself with this.load.start() and wait for its complete event.

Keys: the names of your assets

The first argument is the key. It must be unique per type. Keys are how you refer to the asset later, so choose clear names ('hero', 'coin', 'level1-map'). A typo gives you Phaser's "missing texture" placeholder: a small green box with a diagonal line, a signal that the key was never loaded.

Common loader methods

Method Loads Used with
load.image(key, url) One picture this.add.image
load.spritesheet(key, url, { frameWidth, frameHeight }) A grid of equal frames animated sprites
load.atlas(key, imageUrl, jsonUrl) Packed images with a JSON description efficient sprites (Spritesheets and animation)
load.audio(key, urls) Sound; pass several formats this.sound.add(key)
load.json(key, url) Data this.cache.json.get(key)
load.tilemapTiledJSON(key, url) A level from the Tiled editor tilemaps
load.bitmapFont(key, png, xml) A bitmap font bitmap text
load.svg(key, url, { width, height }) A vector image drawn at a chosen size add.image
load.text, load.xml, load.script Other files custom needs

You can queue a whole folder with this.load.setPath('assets/') so every later URL is relative to it, and shorten names with this.load.setBaseURL(...) when assets live on another server or a CDN.

A progress bar

The loader emits events while it works. The most useful are progress (a number from 0 to 1), fileprogress, filecomplete, loaderror and complete. Here is a complete progress bar pattern in a Boot scene. It queues a handful of small embedded SVG pictures so you can watch the bar move, then shows them. Reading the code top to bottom is the point.

A loading screen with a progress bar

A real game with large files shows the bar for several seconds, which tells the player something is happening instead of a blank screen. Because the files here are tiny, the bar finishes almost instantly. Notice this.textures.exists(key): a handy way to check whether a texture was loaded.

Loading screens in a separate scene

On a bigger project, give loading its own Boot or Preload scene whose only job is to load every asset the game needs, then start the menu:

JavaScript
class Preload extends Phaser.Scene {
  constructor() { super('Preload'); }
  preload() {
    // progress bar code here
    this.load.pack('main', 'assets/pack.json');   // a JSON asset pack lists everything
  }
  create() {
    this.scene.start('Menu');                      // assets stay in the global caches
  }
}

Assets are stored in global caches that belong to the game, not to one scene, so a texture loaded in Preload is available in every other scene. You do not need to load it again.

Making textures without files

You do not need an image file for every shape. Phaser can make textures at runtime, which is great for prototypes, simple art styles and effects.

From a Graphics object

JavaScript
const g = this.add.graphics();
g.fillStyle(0x22c55e).fillRoundedRect(0, 0, 48, 24, 8);
g.generateTexture('button', 48, 24);   // saved under the key 'button'
g.destroy();                           // the helper is not needed any more

From a canvas you draw on yourself

JavaScript
const tex = this.textures.createCanvas('checker', 64, 64);
const ctx = tex.getContext();
ctx.fillStyle = '#334155';
ctx.fillRect(0, 0, 32, 32);
ctx.fillRect(32, 32, 32, 32);
tex.refresh();                         // upload the canvas to the GPU

From a base64 image

this.textures.addBase64('key', 'data:image/png;base64,...') registers an image encoded as text. It loads asynchronously, so wait for the texture's addtexture event before using it. Embedding images this way inflates your code, so it is for tiny icons or tests only.

The example below builds three textures in code (a rounded button, a checkerboard from a canvas, and a star) and uses them as images, without loading a single file.

Textures drawn in code

One texture can be used by many images, and setTint recolors it without a second texture.

When a file fails to load

The loaderror event reports the file that failed (404, wrong path, blocked by the browser). Phaser does not stop the game; it continues without that asset, and objects using the key show the green missing-texture box. Always check the Network tab of the browser developer tools: the failing request and its URL appear in red.

The most common causes:

  • a wrong relative path (case matters on most servers: Hero.png and hero.png are different files);
  • opening the page as file:// instead of through a web server;
  • the file extension is right but the server sends the wrong type;
  • a cross-origin file without the right CORS headers.

Tips for fast loading

  • Compress images (PNG optimizers, WebP) and sounds (OGG/MP3 at modest bitrates).
  • Use atlases so many small sprites arrive as one image.
  • Load only what the current part needs. Large games load level assets in that level's preload.
  • Show progress. Waiting without feedback feels longer than waiting with a bar.
  • Remove what you no longer need with this.textures.remove(key) or this.cache.audio.remove(key) on very large games.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does Phaser call create() relative to loading?

    The loader finishes the queue first, so assets are guaranteed to be available in create.
  2. 2. What does a green box with a diagonal line in your game usually mean?

    That is Phaser's placeholder for a missing texture, typically caused by a wrong key or a failed load.
  3. 3. Which loader event gives a number from 0 to 1 that you can use for a progress bar?

    The progress event passes the fraction of the queue that has loaded.
  4. 4. How can you create a texture without any image file?

    Draw with a Graphics object (or a canvas texture) and register the result with generateTexture or createCanvas.
  5. 5. A texture loaded in a Preload scene: where is it available?

    Textures, audio and JSON are stored in game-wide caches shared by all scenes.

Summary

  • Queue files with this.load.* in preload; Phaser loads them all, then calls create.
  • Every asset has a unique key per type; a wrong key shows the green missing-texture box.
  • Use load.image, spritesheet, atlas, audio, json, svg and tilemap loaders for the common file types.
  • Listen to progress and complete to show a loading bar; put big loading in a Preload scene because caches are global.
  • Prototype with textures you draw in code: generateTexture, createCanvas, addBase64.

Next: Working with Multiple Scenes