Cappielung Cappielung - 1 year ago 88
Javascript Question

Loading sprite sheet in pixi v3

I'm trying to learn Pixi.js for a game I'd like to code, but I'm having the hardest time with one of the most basic tasks: loading a sprite sheet.
The real problem is that Pixi v3 broke compatibility with an old way to load sprites, which was apparently

. All the tutorials I can find use that method, but when I tried to use it, PIXI threw an error telling me to use their
class. I'd prefer to use the most recent release of a library, so that's fair enough.

I looked up their documentation here:

The problem is, the documentation is sparse (it doesn't even describe the methods that belong to the class). I can figure out how to load a single image as a texture...I think... but I want to load sprite sheets! And the most frustrating thing is that the home page prominently announces support for sprite sheet loading. So how do you do it?

The best I've got based on what I could glean is this:

This is my sprite sheet JSON:

"frames": {
"exampleFrame1.png": {
"frame": {"x":0, "y":0, "w":100, "h":100},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0, "y":0, "w":100, "h":100},
"sourceSize": {"w": 100, "h": 100}

"meta": {
"image": "./images/example-sprite-sheet.png"

And this is the code requesting the sprite:

var sprite;
var loader = new PIXI.loaders.Loader("./images", 5);
loader.add('example-sprites', 'example-sprite-sheet.json');
loader.on('complete', onAssetLoad);

function onAssetLoad(){
sprite = PIXI.Sprite.fromFrame("exampleFrame1.png");
//attach sprite to stage etc...

I could be way off-base with that code above, but I can't find anything in Pixi's documentation, and even all the tutorials and examples they have on their site are using the broken

Does anyone know how to do what I'm trying to do in Pixi v3? Or better yet, does anyone know where I can actually find the information I need?

Answer Source

Your code looks fine. I think you just need a forward slash after "images":

var loader = new PIXI.loaders.Loader("./images/", 5);

Also, this is not necessary but you can use 'once' instead of 'on' for your event handler if you only want to need to listen for it once.

loader.once('complete', onAssetLoad);

Go here for some great examples: