how to load an image in @ion-phaser/react npm package

Viewed 629
/**
 * @flow
 */

import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'
import logo from './assets/logo.png'
import sky from './assets/sky.png'
import star from './assets/star.png'
import platformPic from './assets/platform.png'
import dude from './assets/dude.png'
import bomb from './assets/bomb.png'

import './App.css'


class App extends Component {

state = {
    unmounted: false,
    initialize: false,
    game: {
        width: "800",
        height: "600",
        type: Phaser.AUTO,
        physics:{
            default: 'arcade', 
            arcade: {
                gravity: {y: 200}, 
                debug: false
            }, 
        }, 
        scene: {
        init: function() {
            // this.cameras.main.setBackgroundColor('#24252A')
        },
          preload: function() {
            this.load.image('sky', '/assets/sky.png');

          },
          create: function() { 
              let platforms;
              this.add.image(400, 300, 'sky').setOrigin(0.5);
          },
          update: function(){

          },
        }
    },
}


initializeGame = () => {
  this.setState({ initialize: true })
}



render() {
const { initialize, game, unmounted } = this.state
return (
    <div>

       { !initialize &&
        <React.Fragment>
          <img src={logo} className="App-logo" alt="logo" />
          <div onClick={this.initializeGame} className="flex">
            <a href="#1" className="bttn">Initialize</a>
          </div>
        </React.Fragment>
      }
      { !unmounted && <IonPhaser game={game} initialize={initialize} /> 
}


    </div>
);
}
}
export default App;

I did get another example working with phaser working for the example on ion-phasers react example github page with react and electron. I think it works faster in electron than in the browser.

the code above image uploading does not work it shows green boxes with a diagnol in it instead of picture. trying to complete the beginner tutorial on phaser 3 webpage converting it to work with ion-phaser in react. Please help!

1 Answers

Your code where it says:

preload: function() {
        this.load.image('sky', '/assets/sky.png');

      },

Should say

preload: function() {
        this.load.image('sky', sky);

      },

instead, since you already imported it at the top with:

import sky from './assets/sky.png'

What you did wrong was you already imported the image under the name 'sky' but you try to load the image by its full path instead.

This is an older question but i was having the same issue and figured it out so i thought I'd answer the question :)

Related