要在网页中实现“全屏游戏窗口化”(即让游戏窗口占据整个屏幕),通常需要使用 HTML5 的 <canvas> 标签结合 JavaScript 来实现。以下是一个基本的实现方法,包括如何将游戏窗口设置为全屏、处理键盘输入、更新游戏状态和渲染画面。
✅ 一、基本结构(HTML + CSS + JS)
1. HTML 结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全屏游戏</title>
<style>
html, body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="game.js"></script>
</body>
</html>
✅ 二、JavaScript 实现(game.js)
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 设置 canvas 全屏
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 窗口 resize 时重新设置 canvas
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// 游戏逻辑
let score = 0;
let gameRunning = true;
function draw() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制游戏元素(比如一个简单的矩形)
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 更新游戏状态(比如分数)
ctx.fillStyle = 'white';
ctx.font = '20px Arial';
ctx.fillText(`Score: ${score}`, 10, 30);
}
// 游戏循环
function gameLoop() {
if (!gameRunning) return;
draw();
requestAnimationFrame(gameLoop);
}
// 开始游戏
gameLoop();
// 键盘输入
document.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
// 按下空格键,暂停/继续游戏
gameRunning = !gameRunning;
}
});
✅ 三、如何让游戏窗口全屏?
你已经通过以下方式让游戏窗口全屏:
canvas.width = window.innerWidth; canvas.height = window.innerHeight;- 监听
resize事件,动态调整 canvas 大小 - 确保
html和body的overflow设置为hidden
✅ 四、可选扩展功能
-
全屏模式(Fullscreen)
使用requestFullscreen()或mozRequestFullScreen()(Firefox)来进入全屏模式。canvas.requestFullscreen();退出全屏:
document.exitFullscreen(); -
鼠标/键盘控制
可以添加鼠标或键盘控制游戏对象。 -
动画与物理引擎
使用如 Phaser、Pixi.js 等游戏引擎来实现更复杂的动画和物理效果。
✅ 五、总结
| 功能 | 实现方式 |
|---|---|
| 全屏设置 | canvas.width = window.innerWidth; canvas.height = window.innerHeight; |
| 窗口 resize | window.addEventListener('resize', ...) |
| 游戏循环 | requestAnimationFrame(gameLoop) |
| 键盘控制 | document.addEventListener('keydown', ...) |
| 全屏模式 | canvas.requestFullscreen(); |
如果你有具体的游戏逻辑(比如移动、碰撞检测、动画等),可以告诉我,我可以帮你扩展代码。