javascript - 在执行过程中动态自动缩放 Phaser 3 游戏

标签 javascript html css phaser-framework

我想知道是否有一种方法可以使用设定的分辨率来开发我的游戏,例如:

width: 1000,
height: 600,

然后让 HTML 或 Phaser 在窗口大小发生变化时自动缩放 Canvas 元素。

我试过用这个:

width: window.innerWidth / 2,
height: window.innerHeight / 2,

但这不会保留纵横比,不会正确缩放 Sprite /图像,需要重新加载页面进行调整,这意味着我无法使用特定的 x/y 坐标。

我查看了 Phaser 3 的 Scale manager 和 Flex Boxes,但它们似乎并没有改变 Canvas 大小。

最佳答案

我能找到的最简单的解决方案如下:

  • 首先,添加这些 CSS 样式规则:
html, body {
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
  background: #111;
  color: #eee;
  font: caption;
}

canvas {
  /* And see postBoot() in JS */
  width: 100%;
  height: 100%;
  object-fit: contain;
  /* <https://caniuse.com/#feat=object-fit> */
}

#version {
  position: absolute;
  left: 5px;
  top: 605px;
}
  • 其次,在config对象中添加一个回调函数来覆盖Phaser的默认样式,如下所示:
var config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  physics: {
    default: "arcade",
    arcade: {
      gravity: { y: 200 }
    }
  },
  scene: {
    preload: preload,
    create: create
  },
  callbacks: {
    postBoot: function (game) {
      // In v3.15, you have to override Phaser's default styles
      game.canvas.style.width = '100%';
      game.canvas.style.height = '100%';
    }
  }
};

我找到了代码示例 here .

编辑:

如果您希望游戏在执行过程中窗口更改时调整大小,您可以在更新循环中创建类似的函数,如下所示:

function update(){
    (function() {
        const gameId = document.getElementById("game"); // Target div that wraps the phaser game
        gameId.style.width = '100%'; // set width to 100%
        gameId.style.height = '100%'; // set height to 100%
    })(); // run function
}

关于javascript - 在执行过程中动态自动缩放 Phaser 3 游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58375035/

相关文章:

javascript - 是否可以在 HTML/JavaScript 中构建原生样式的切换按钮?

background - 在 CSS 中使用背景渐变与使用图像相比性能如何?

javascript - 为什么我的方法没有返回对象

javascript - 使用 moment.js 时的弃用警告

javascript - 将新的 Google Sheets 数据附加到 BigQuery 表中

javascript - document.CreateElement(div) 不起作用...

javascript - 使用 Google Chrome 扩展程序检测 Flash Player 全屏模式并在其上注入(inject) CSS

html - 如何在 HTML 电子邮件 css 中对齐表格

css - 在 IE5.x 中居中 div?

jquery - 查找鼠标当前指向的 html 元素的 font-family?