Skip to content

resources

Olivier Biot edited this page Apr 5, 2026 · 12 revisions

Resources & Asset Loading

melonJS provides a resource loader to preload images, audio, maps, fonts, and other assets before your game starts.

Defining Resources

Resources are defined as an array of objects with name, type, and src properties:

const resources = [
    // images
    { name: "player",   type: "image", src: "data/img/player.png" },
    { name: "tileset",  type: "image", src: "data/img/tileset.png" },

    // texture atlas (JSON + image)
    { name: "sprites",  type: "json",  src: "data/img/sprites.json" },
    { name: "sprites",  type: "image", src: "data/img/sprites.png" },

    // Tiled maps
    { name: "level1",   type: "tmx",   src: "data/map/level1.tmx" },
    { name: "level1",   type: "tmx",   src: "data/map/level1.json" },

    // audio (provide path without extension — melonJS picks the best format)
    { name: "bgm",      type: "audio", src: "data/bgm/" },
    { name: "jump",     type: "audio", src: "data/sfx/" },

    // bitmap font
    { name: "PressStart2P", type: "binary", src: "data/font/PressStart2P.fnt" },
    { name: "PressStart2P", type: "image",  src: "data/font/PressStart2P.png" },

    // web font
    { name: "MyFont",   type: "fontface", src: "data/font/myfont.woff2" },
];

Preloading

Load all resources at once using loader.preload(), with a callback for when everything is ready:

import { loader, state } from "melonjs";

loader.preload(resources, () => {
    // all assets loaded — start the game
    state.change(state.PLAY);
});

Resource Types

Type Description
image PNG, JPG, or other image files for sprites and tilesets
json JSON data files (texture atlas, custom data)
tmx / tsx Tiled map and tileset files (XML or JSON format)
audio Sound effects and music (MP3, OGG — provide directory path)
binary Raw binary/text data (bitmap font .fnt files, custom formats)
fontface Web font files (WOFF2, TTF) loaded as CSS font-face
xml XML data files
video Video files for video sprites

Accessing Loaded Resources

After preloading, access resources through the loader:

import { loader } from "melonjs";

const image = loader.getImage("player");
const json = loader.getJSON("sprites");
const tmx = loader.getTMX("level1");

Lazy Loading

To load a single resource after the initial preload:

loader.load(
    { name: "bonus", type: "image", src: "data/img/bonus.png" },
    () => { console.log("bonus loaded"); },
    () => { console.error("failed to load bonus"); }
);

Loader Options

Configure cross-origin and caching settings:

loader.setOptions({
    crossOrigin: "anonymous",
});

Audio Setup

Initialize the audio engine before preloading:

import { audio } from "melonjs";

audio.init("mp3,ogg");

This tells melonJS which audio formats to try, in order of preference.

Clone this wiki locally