下面是一个基于 Canvas 的小游戏的实现步骤:
- 创建 HTML 文件,并在其中添加一个 Canvas 元素:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas Game</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
- 在 JavaScript 文件中获取 Canvas 元素,并设置其宽度和高度:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 400;
- 创建一个游戏循环函数,并在其中绘制一个矩形:
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, 50, 50);
}
setInterval(gameLoop, 10);
- 现在,我们可以在 Canvas 上看到一个蓝色的矩形。我们可以使用键盘事件来移动这个矩形。为此,我们需要创建一个变量来存储矩形的位置,并在游戏循环函数中更新它:
let x = 0;
let y = 0;
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(x, y, 50, 50);
}
setInterval(gameLoop, 10);
document.addEventListener('keydown', function(event) {
if (event.code === 'ArrowRight') {
x += 5;
} else if (event.code === 'ArrowLeft') {
x -= 5;
} else if (event.code === 'ArrowDown') {
y += 5;
} else if (event.code === 'ArrowUp') {
y -= 5;
}
});
- 现在,我们可以使用箭头键来移动矩形了。最后,我们可以添加一些障碍物,并检测矩形是否与障碍物相撞。这可以通过创建一个数组来实现,该数组存储障碍物的位置,并在游戏循环函数中检查矩形是否与任何障碍物相撞:
let x = 0;
let y = 0;
const obstacles = [{x: 200, y: 200}, {x: 300, y: 300}];
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(x, y, 50, 50);
obstacles.forEach(function(obstacle) {
ctx.fillStyle = 'red';
ctx.fillRect(obstacle.x, obstacle.y, 50, 50);
if (x < obstacle.x + 50 && x + 50 > obstacle.x && y < obstacle.y + 50 && y + 50 > obstacle.y) {
console.log('Collision detected!');
}
});
}
setInterval(gameLoop, 10);
document.addEventListener('keydown', function(event) {
if (event.code === 'ArrowRight') {
x += 5;
} else if (event.code === 'ArrowLeft') {
x -= 5;
} else if (event.code === 'ArrowDown') {
y += 5;
} else if (event.code === 'ArrowUp') {
y -= 5;
}
});
以上就是实现一个基于 Canvas 的小游戏的基本步骤