fbpx

Make a Phaser Game Responsive

I got the majority of the code below from a great Stack Overflow post that I can no longer find. I adjusted it a bit to make the calculations based on the width of the parent container, rather than the width of the window.

STEP 1: Update the create function

You need to add the two lines of code below to the top of your create function.

function create ()
{
    window.addEventListener('resize', resize);
    resize();

    // Place the remaining create function code below
}

STEP 2: Add the resize function

Add the following function to the JavaScript file that includes the Phaser create function. Please note that the function assumes that an element with a class called parent-container wraps the phaser game on your page. If you would instead like to check the width of the screen, replace document.getElementsByClassName(“parent-container”)[0].offsetWidth with window.innerWidth. And, if you would instead like to check the width of the body element, use document.body.clientWidth.

function resize() {
        var canvas = game.canvas, width = document.getElementsByClassName("parent-container")[0].offsetWidth, height = window.innerHeight;
    var wratio = width / height, ratio = canvas.width / canvas.height;

    if (wratio < ratio) {
        canvas.style.width = width + 'px';
        canvas.style.height = (width / ratio) + 'px';
    } else {
        canvas.style.width = (height * ratio) + 'px';
        canvas.style.height = height + 'px';
    }
}

That’s all there is to it! To see this in action, check out a game that we created at https://blog.wplauncher.com/intrinsic-motivation-mastery-game.

Leave a Reply

Your email address will not be published. Required fields are marked *