canvas实习飞机大战小游戏
具体实现代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>飞机大战</title>
<style>
canvas {
border: 1px solid;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas width="500px" height="800px"></canvas>
<script>
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
// 初始化数据
var START = 0;
var STARTING = 1;
var RUNNING = 2;
var PAUSE = 3;
var GAMEOVER = 4;
// 记录游戏的状态变化
var state = START;
// 获取画布的宽和高
var HEIGHT = canvas.height;
var WIDTH = canvas.width;
// 游戏的分数
var score = 0;
// 我方飞机的生命值
var life = 3;
// 将游戏分为几个阶段
// 1 准备阶段 使用定时器绘制背景图和logo
// 1.1 运动的背景图片
// 1.1.1创建图片对象
var bg = new Image();
bg.src = "img/background.png"
// 定义图片信息
var BG = {
width: WIDTH,
height: HEIGHT,
img: bg
}
// 创建背景图片的构造函数
function Bg(parmas) {
this.width = parmas.width;
this.height = parmas.height;
this.img = parmas.img;
// 绘制图片的坐标
this.x = 0;
this.y = 0;
this.x1 = 0;
this.y1 = -this.height;
// 定义绘制图片的方法
this.paint = function () {
ctx.drawImage(this.img, this.x, this.y, this.width, this.height)
ctx.drawImage(this.img, this.x1, this.y1, this.width, this.height)
}
// 图片的运动
this.step = function () {
this.y += 10;
this.y1 += 10;
if (this.y1 >= this.height) {
this.y1 = -this.height;
}
if (this.y >= this.height) {
this.y = -this.height;
}
}
}
var sky = new Bg(BG)
// 1.2 logo
// 1.2.1创建logo对象
var logo = new Image();
logo.src = "img/start.png"
// 2 游戏加载阶段 点击画布触发开始游戏
// 2.1点击canvas触发当前状态
canvas.onclick = function () {
if (state == START) {
state = STARTING;
}
}
// 2.2 绘制我方飞机
// 把图片的地址存入数组中
var imgArr = ["img/game_loading1.png", "img/game_loading2.png", "img/game_loading3.png",
"img/game_loading4.png"
]
var img = [];
for (var i = 0; i < imgArr.length; i++) {
img[i] = new Image();
img[i].src = imgArr[i]
}
var LOADING = {
imgs: img,
length: img.length,
width: 186,
height: 38
}
// 创建构造函数
function Loading(parmas) {
this.imgs = parmas.imgs;
this.length = parmas.length;
this.width = parmas.width;
this.height = parmas.height;
// 记录当前照片索引值
this.startIndex = 0;
// 开始绘制
this.paint = function () {
// console.log(loading);
ctx.drawImage(this.imgs[this.startIndex], 0, HEIGHT - this.height)
this.startIndex++;