Case
Case

Reputation: 4272

Phaser loading images dynamically after preload

With Phaser I am working on a game. This game rewards the player with an item that is not capable of being preloaded. After an Ajax call I was hoping to load the image and then display it in the phaser animation. Is there anyway to do this?

Flow: Game is playing Game Completes and Ajax Call is made. Ajax responds with which image to use. Phaser loads image and displays what they won.

Upvotes: 9

Views: 9777

Answers (2)

Siddhartha
Siddhartha

Reputation: 151

Lazzy loading in Phaser 3 can be done by using the Phaser.Loader.LoaderPlugin(scene)

lazzyLoading:function(){
        var name = 'card-back';
        // texture needs to be loaded to create a placeholder card
        const card = this.add.image(WIDTH/2, HEIGHT/2, name);

        let loader = new Phaser.Loader.LoaderPlugin(this);
        // ask the LoaderPlugin to load the texture
        loader.image(name, 'assets/images/demon-large1.png');

        loader.once(Phaser.Loader.Events.COMPLETE, () => {
            // texture loaded so use instead of the placeholder
            card.setTexture(name)
        });
        loader.start();
    }

Upvotes: 3

Billy
Billy

Reputation: 886

You can use Phaser's loader to load an image at anytime by invoking

game.load.image('referenceName', 'assets/pics/file.jpg');

then you can set an event like the ones at http://phaser.io/examples/v2/loader/load-events

game.load.onLoadComplete.add(aFunctionToCall, this);

But most importantly don't forget to actually tell the loader to start after you've set everything up.

game.load.start();

Upvotes: 21

Related Questions