I'm trying to load image assets for PIXI.js in a React project of mine that uses Webpack. Here is my whole 'Menu' component class:
import React from 'react';
import styles from './Menu.css';
import backgroundUrl from './background.jpg';
require('pixi.js')
class Menu extends React.Component {
componentDidMount () {
// Get reference to canvas element
this.canvas = this.refs.canvas;
// Load assets
PIXI.loader.add([
{
name: 'background',
url: backgroundUrl
}
]).load(this.init());
}
init () {
// Create background sprite
const background = new PIXI.Sprite(PIXI.loader.resources.background.texture);
// DEBUG: Height and width is always '1'
console.log('Background width: ' + background.width);
console.log('Background height: ' + background.height);
// Setup renderer
this.renderer = PIXI.autoDetectRenderer(background.width, background.height);
this.renderer.autoResize = true;
this.renderer.resize(window.innerWidth, window.innerHeight);
this.canvas.appendChild(this.renderer.view);
// Create stage
this.stage = new PIXI.Container();
// Add background to stage
this.stage.addChild(background)
// Tell the renderer to render the stage
this.renderer.render(this.stage);
}
render () {
return (
<div className={styles.canvas} ref='canvas'></div>
);
}
}
export default Menu;
Now as you can see, I'm trying to load the image background.jpg into PIXI with the loader.add() function. It just doesn't work. In my debug console logs I can see that the height and width of the image is 1. Also, when I view the URL for the background image, it all seems fine. Any tips?
Try switching it to this;
~
.load(() => this.init());
~
@staff0rd that works great! But.. why??
load expects a function as its parameter, however you were actually calling init() thereby passing the result of it (void) to load. If init didn't have references to this inside it, you could use the following to pass the function;
~
.load(this.init);
~
Notice the lack of parentheses.
this is obsolete now... and we need a way to load any asset which we're bundling with webpack
@hayesmaker it works but the texture is empty for a while. when it's ready it gets blitted correctly.
@nitwhiz is that why I initially get a 1px width for all sprites?
is there a way to get a callback to fire once a sprite is loaded?
Most helpful comment
this is obsolete now... and we need a way to load any asset which we're bundling with webpack