Reputation: 4318
import React, { Component } from 'react';
import Phaser from 'phaser';
export default class App extends Component {
constructor(props) {
super(props);
this.game = null;
this.create = () => {
this.game.stage.backgroundColor = '#124184';
}
}
componentDidMount() {
this.game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-target',
{
create: this.create
}
);
console.log(this.create);
}
render() {
return (
<section id="phaser-target">
hello there old friend
</section>
)
}
}
So I create the Phaser game object, in the component did mount method, note that my html
looks like this:
<body style="overflow: hidden;">
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"><section><section id="phaser-target">hello there old friend</section></section></div>
<script type="text/javascript" src="/static/js/bundle.js"></script>
<canvas width="1024" height="768"></canvas></body>
The canvas is being rendered outside of the target element.
And also, my this.create
function, i never actually get in there. I console.log
but it never gets in.
I'm re-reading the code, and to me it all makes sense and it should work but i don't understand why it isn't.
Could anyone give me some guidance?
Upvotes: 7
Views: 2465
Reputation: 1285
You don't mention what version of Phaser you're using, which is quite important since the API has changed many times over the years.
This answer assumes you're using the current latest version of Phaser (3.1.4)
```
var config = {
type: Phaser.AUTO,
parent: 'phaser-parent',
pixelArt: true,
width: 800,
height: 600,
scene: {
preload: this.preload.bind(this),
create: this.create.bind(this)
}
};
var game = new Phaser.Game(config);
```
Set the parent config to be the id of your phaser-parent. and it should append to the correct element.
I'm guessing the problem is Phaser is not detecting this and automatically appending to the document body element.
To correctly call the create method you should make create a normal ES6 class method:
create() {
//do stuff
}
now you should call it with bind(this):
this.create.bind(this)
and you should read up on React documentation scoping inside ES6 classes. There's a section here on why binding this is necessary for events, and it's the same reason you need to do it here
https://reactjs.org/docs/handling-events.html
Upvotes: 3