Using Phaser together with React

感情迁移 提交于 2020-01-02 04:33:05

问题


I am trying to understand how I could use React for rendering all the UI elements and Phaser for rendering a game (using Canvas or WebGL) within the React application.

One way would be to use React's componentDidMount, so after I have my HTML ready I can use a div id to render the Phaser content. In this case who does the rendering? React of Phaser?

If the mentioned way is not the right one, could you suggest another?


回答1:


There is a module for this on Github called react-phaser. Here is a CodePen that does not use any separate module.

var PhaserContainer = React.createClass({

    game: null,
    ...
    componentDidMount: function(){
        this.game = new Phaser.Game(800, 400, Phaser.AUTO, "phaser-container", 
        { 
            create: this.create,
            update: this.update
        });
    },
    ...
    render: function(){
        return (
            <div className="phaserContainer" id="phaser-container">
            </div>
        );
    }
    ...
}

This is not my CodePen. Credit goes to Matthias.R




回答2:


Check this new WebComponent to integrate Phaser with any other framework 👍 https://github.com/proyecto26/ion-phaser

Example:

import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'

class App extends Component {
  state = {
    initialize: false,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {}
    }
  }
  render() {
    const { initialize, game } = this.state
    return (
      <IonPhaser game={game} initialize={initialize} />
    )
  }
}


来源:https://stackoverflow.com/questions/48682260/using-phaser-together-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!