tazer900
tazer900

Reputation: 39

Unable to display a simple image in Phaser

So I wanted to use Phaser for a project I'm trying to make. I was following the tutorial on their website, but then I hit a bare wall. In one of the lines I wrote, it said this:

function create() {
  this.add.image(400, 300, 'sky');
}

I read the article, and it is supposed to display a picture of a sky (which I imported into my project beforehand), but it is still a blank screen.

I tried a lot of things so far but it is still not working. Can someone help?

Here's all the relevant config:

var config = {
 type: Phaser.AUTO,
 width: 800,
 height: 600,
 scene: {
 preload: preload,
 create: create,
 update: update,
 },
};

And Code:

var game = new Phaser.Game(config);

//Loads in sprites
function preload() {
  this.load.image('sky', 'assets/sky.png');
  this.load.image('ground', 'assets/platform.png');
  this.load.image('star', 'assets/star.png');
  this.load.image('bomb', 'assets/bomb.png');
  this.load.spritesheet('dude', 'assets/dude.png', {
    frameWidth: 32,
    frameHeight: 48,
  });
}

//Displays sprites
function create() {
  this.add.image(400, 300, 'sky');
}

//Update loop
function update() {}

Upvotes: 3

Views: 742

Answers (1)

winner_joiner
winner_joiner

Reputation: 14695

Check the urls of the assets, in your code, with the project folder structure on playcode.io. Tried to run the code on playcode and it seems to works:
(atleast when you publish the website. The webpreview freezes/crashes, I have to assume, that this is a issue of codeplay.io in conjunction with with the phaser framework)

Editor: screenshot playcode.io

Result: screenshot result browser

link to the working demo

Update (if you need the preview):

Since it seems that the preview on playcode.io uses temp files and the Urls don't really match the real file - structure, you could use this workaround, to side step this issue.
Just:

  1. For any image, that you want to load in phaser, load it image simply in html.
    example: <img id="sky" src="assets/sky.png" style="width:1px;height:1px;" />
  2. And in the phaser preload function replace all this.load.image with this.textures.addImage
    Here a link to the documentation

Here a example:

Replace the line of code:

this.load.image('sky', 'assets/sky.png');

with this one:

this.textures.addImage('sky', document.getElementById('sky')); 

Since it seems, that playcode preview cannot handle generating images-urls from javascript, you could use this workaround. BUT only for development on playcode, for production, or when you publish use the original this.load.image(...). the workaround works also on production, but is not optimal and not recommended.

Upvotes: 2

Related Questions