asset type
parser function, as described above
// a texture generated in code rather than loaded, baked behind the
// loading screen and read back by name
const skies = new Map();
loader.setParser("sky", (asset, onload, onerror) => {
bakeSky(asset.name) // the game's own generator, returning a Promise
.then((canvas) => {
skies.set(asset.name, canvas);
onload();
}, onerror);
return 1;
});
await loader.preload([{ name: "nebula", type: "sky" }]);
const backdrop = new Sprite(0, 0, { image: skies.get("nebula") });
// a file format of your own, fetched from `src`
const levels = new Map();
loader.setParser("csv", (asset, onload, onerror) => {
fetch(asset.src)
.then((response) => {
// a 404 still resolves: without this the error page is parsed
if (!response.ok) {
throw new Error(`${asset.src}: HTTP ${response.status}`);
}
return response.text();
})
.then((text) => {
levels.set(asset.name, text.split("\n").map((row) => row.split(",")));
onload();
})
.catch(onerror);
return 1;
});
loader.setBaseURL("csv", "data/levels/");
await loader.preload([{ name: "level1", type: "csv", src: "level1.csv" }]);
Teach the loader an asset type of your own, or replace the parser of an existing one.
Once registered, an entry of that
typegoes in a preload list like any other: loader.preload counts it as one step of the progress bar and waits for it beforeLOADER_COMPLETE. That makes it the place for work that is not a download at all, such as a texture generated in code: done here it happens behind the loading screen, rather than on the first frame of the stage that needs it.The parser is called as
parserFn(asset, onload, onerror, settings):assetis the preload entry,{ name, type, src, ... }.srcis optional, so{ name, type }is a complete entry for something generated.onload()once the asset is ready, oronerror(error)if it failed. Exactly one of them, now or later.1if it will call one of them, or0when there is nothing to load, in which case the loader moves on without waiting.onloadtakes no value, and the loader keeps nothing for a type it does not know: keep the result yourself (aMapkeyed byasset.name, say) and read it from there.Register before preloading. Registering the same type twice logs a warning, so do it once rather than in code that runs on every scene. A
srcis prefixed by loader.setBaseURL only when one is set for this type by name: the"*"wildcard does not cover custom types.