Wednesday, 10 October 2018

Rendering Phaser.io canvas in a react component

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?



from Rendering Phaser.io canvas in a react component

No comments:

Post a Comment