如何使用Phaser 3使画布响应式?

Kot*_*kit 6 phaser-framework

以前我在Phaser 2上工作,但现在我需要切换到Phaser 3。

我试图使画布具有响应能力,ScaleManager但无法正常工作。

我认为某些方法已更改,但我没有找到任何帮助重新调整全屏舞台大小的方法。

var bSize = {
  bWidth: window.innerWidth ||
    root.clientWidth ||
    body.clientWidth,
  bHeight: window.innerHeight ||
    root.clientHeight ||
    body.clientHeight,
};

var game;

var canvas = document.getElementById("canvas");

function create() {

    // Scaling options
    game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;

    // Have the game centered horizontally
    game.scale.pageAlignHorizontally = true;

    // And vertically
    game.scale.pageAlignVertically = true;

    // Screen size will be set automatically
    game.scale.setScreenSize(true);
}

window.onload = function() {

    // Create game canvas and run some blocks
    game = new Phaser.Game(
        bSize.bWidth, //is the width of your canvas i guess
        bSize.bHeight, //is the height of your canvas i guess
        Phaser.AUTO, 
        'frame', { create: create });

    canvas.style.position = "fixed";
    canvas.style.left = 0;
    canvas.style.top = 0;  
}
Run Code Online (Sandbox Code Playgroud)

Edm*_*mer 9

从v3.16.0开始,请使用Scale Manager。简而言之:

var config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.FIT,
        parent: 'phaser-example',
        autoCenter: Phaser.Scale.CENTER_BOTH,
        width: 800,
        height: 600
    },
    //... other settings
    scene: GameScene
};

var game = new Phaser.Game(config);
Run Code Online (Sandbox Code Playgroud)

是完整的代码,是使用“ 比例管理器”的一些有用示例。

  • `未捕获的类型错误:无法读取未定义的属性'FIT'` - 我做错了什么? (2认同)

Fab*_*ous 6

Phaser 3 还没有规模管理器,但它正在开发中。现在我建议遵循本教程。它基本上使用一些 CSS 将画布居中,然后调用调整大小函数,该函数在窗口发出调整大小事件时处理保持游戏比例。

这是上面链接的教程中使用的代码:CSS:

canvas {
    display: block;
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)

调整大小功能:

function resize() {
    var canvas = document.querySelector("canvas");
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var windowRatio = windowWidth / windowHeight;
    var gameRatio = game.config.width / game.config.height;

    if(windowRatio < gameRatio){
        canvas.style.width = windowWidth + "px";
        canvas.style.height = (windowWidth / gameRatio) + "px";
    }
    else {
        canvas.style.width = (windowHeight * gameRatio) + "px";
        canvas.style.height = windowHeight + "px";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

window.onload = function() {
    //Game config here
    var config = {...};
    var game = new Phaser.Game(config);
    resize();
    window.addEventListener("resize", resize, false);
}
Run Code Online (Sandbox Code Playgroud)