anskotid

Using Phaser together with React

Recommended Posts

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. But in this case React does the game rendering too.

Is there any way to achieve the desired result?

Share this post


Link to post
Share on other sites

There are a couple of approaches, there are also a couple of threads on this so try searching for more info.

Your proposal is fine, and by far the easiest solution. React does its normal thing for your UI, but you expose a canvas element and initialise the Phaser stuff when it mounts. However, as you probably don't want to unmount and remount that component its not a great improvement over just having a canvas sat there in the DOM.

There are also a couple of modules out there that swap React's DOM rendering layer with a canvas rendering layer, although that won't work with Phaser.

Bare in mind also that if you're really pushing rendering perf then any elements overlapping the canvas element will have an effect on canvas refresh rates, depending on your style of game this may or may not be a major problem.

Share this post


Link to post
Share on other sites

You can definitely do something like this. 

I'd recommend checking out Preact as an alternative to React if you're only going to be using it for Game UI. Pretty much everything you get with React in a package that's ~3kb. The approach I'd recommend is to have a (P)react component that renders your Phaser canvas element, and have that component's shouldComponentUpdate method always return false. That way the game won't reload every time there's a change to the UI and you can take advantage of state changes in your UI without impacting the rendering of the game.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.