本文旨在提供一种在Phaser 3中实现游戏画布 响应式布局 的实用方法。通过调整缩放模式和CSS样式,使游戏画布能够自适应父容器的大小,并保持内容居中显示,即使在 浏览器 窗口大小调整时也能保证最佳的视觉效果。本文将提供详细的代码示例,帮助开发者轻松实现这一功能。
在Phaser 3中,实现游戏画布的响应式布局,使其能够根据父容器的大小自动调整,并保持内容居中显示,是一个常见的需求。以下提供一种基于`Phaser.Scale.HEIGHT_CONTROLS_WIDTH`缩放模式的实现方法,结合CSS样式,可以达到较好的效果。 ### HTML结构 首先,需要在HTML中创建一个父容器,用于承载Phaser 3游戏画布。 ``` htmlhtml, body {
width: 100%;
height: 100%;
overflow: hidden;
}
#parent {
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 80vh;
}const config = {
type: Phaser.AUTO,
backgroundColor: '#282c34',
scale: {
mode: Phaser.Scale.HEIGHT_CONTROLS_WIDTH,
parent: 'parent',
width: '100%',
height: '100%',
autoCenter: Phaser.Scale.CENTER_BOTH
},
scene: {
preload: preload,
create: create
}
};
const game = new Phaser.Game(config);
function preload ()
{
this.load.setBaseURL('http://labs.phaser.io');
this.load.image('sky', 'assets/skies/space3.png');
this.load.image('logo', 'assets/sprites/phaser3-logo.png');
this.load.image('red', 'assets/particles/red.png');
}
function create ()
{
this.add.image(400, 300, 'sky');
var particles = this.add.particles('red');
var emitter = particles.createEmitter({
speed: 100,
scale: { start: 1, end: 0 },
blendMode: 'ADD'
});
var logo = this.physics.add.image(400, 100, 'logo');
logo.setVelocity(100, 200);
logo.setBounce(1, 1);
logo.setCollideWorldBounds(true);
emitter.startFollow(logo);
}// Game Screen
create(){
this.scale.on('resize', this.resize, this);
}
resize (gameSize: { width: any; height: any; }, baseSize: any, displaySize: any, resolution: any){
this.cameras.resize(displaySize._parent._width, displaySize._parent._height);
}