javascript - 在执行过程中动态自动缩放 Phaser 3 游戏
问题描述
我想知道是否有办法以设定的分辨率开发我的游戏,例如:
width: 1000,
height: 600,
然后让 HTML 或 Phaser 在窗口大小发生变化时自动缩放画布元素。
我试过用这个:
width: window.innerWidth / 2,
height: window.innerHeight / 2,
但这不能保留纵横比,不能正确缩放精灵/图像,需要重新加载页面进行调整,这意味着我不能使用特定的 x/y 坐标。
我查看了 Phaser 3 的 Scale manager 和 Flex Boxes,但它们似乎并没有改变画布大小。
解决方案
我能找到的最简单的解决方案如下:
- 首先,添加这些 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%';
}
}
};
我在这里找到了代码示例。
编辑:
如果您希望游戏在执行过程中更改窗口时调整大小,您可以在更新循环中执行类似的功能,如下所示:
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
}
推荐阅读
- c# - WPF:用户控件数据上下文绑定不反映对 ViewModel 的更改
- c# - NPOI Excel - 如何在不保存的情况下返回 FileStream?
- c# - 在第一次触摸 android unity2D 平台游戏时有一次小滞后
- rest - Xena 用户成员资格返回所有行
- javascript - 关闭模态对话框到另一个模态对话框
- c# - 如何从存储 uri 中提取存储帐户名称和 blob 名称
- angular - 如何将 netlify 函数连接到我的 Angular 应用程序
- amazon-s3 - S3 存储桶的 ListObjectsV2 操作的 AccessDenied
- python - 为另一列指定一个条件时如何填充前向值?
- c - 链表头总是设置为NULL