canvas绘制飞机大战

使用canvas绘制飞机大战主要分为一下5个状态 再根据5个状态逐步分析就很简单了 下面的的代码注释
应该很详细了 当然下面有些可以简略来写的 比如引入图片之类的
第一阶段:游戏欢迎状态 0 START
第二阶段:游戏加载状态 1 LOADING
第三阶段:游戏运行状态 2 RUNNING
第四阶段:游戏暂停阶段 3 PAUSE
第五阶段:游戏结束阶段 4 GAMEOVER

<script type="text/javascript">
var canvas = document.getElementById("canvas");
// console.log(canvas);
var cxt = canvas.getContext("2d");


// 1.记录初始化信息 定义游戏状态
const START = 0,//const定义常量(一般大写表示常量 常量一般是不能修改的)  var定义变量
    LOADING = 1,
    RUNNING = 2,
    PAUSE = 3,
    GAMEOVER = 4;
//1.给定一个状态 然后根据这个状态来与上面的常量进行比较 判断游戏处与哪个状态
var state = 0;
//2.定义游戏得分
var score = 0;
//3.定义我方飞机的生命值
var life = 3;
//4.设置宽度和高度
var WIDTH = 480,
    HEIGHT = 650;

//1.第一阶段:游戏欢迎状态   0     		START

//1.1引入背景图
var bg = new Image();
bg.src = "images/background.png";

//1.1.1需要图片的地址 宽度 高度)
var obj = {
    imgs:bg,
    width:480,
    height:852
}
//1.1.2背景图片的构造函数
function BG(config){//config此时传的是obj
    this.imgs = config.imgs;//config.imgs相当于obj.imgs
    this.width = config.width;
    this.height = config.height;
    //开始绘制 清楚绘制的坐标
    this.x1 = 0;
    this.y1 = 0;
    this.x2 = 0;
    this.y2 = -this.height;

    //绘制图片的方法
    this.paint = function(){
        cxt.drawImage(this.imgs,this.x1,this.y1);
        cxt.drawImage(this.imgs,this.x2,this.y2);
    }

    //运动方法
    this.step = function(){
        // 控制两张背景图片向下运动
        this.y1++;
        this.y2++;
        //判断两张图片的零界点
        if(this.y1 ==  this.height){//当第一张图运动到最底下时 此时y为820
            this.y1 = -this.height;//然后把第二张图放到第一张图上面 此时为-820
        }
        else if(this.y2 == this.height){//当第二张图运动到最底下时
            this.y2 = -this.height;//然后把第二张图放到第一张图的上面
        }
    }
}
//创建背景对象
var sk = new BG(obj);

//1.2创建logo
var logo = new Image();
logo.src = "images/start.png";

//2.第二阶段:游戏加载状态   1			LOADING

//2.1加载游戏过程中的图片
var loadings = [];
loadings[0] = new Image();
loadings[0].src = "images/game_loading1.png";
loadings[1] = new Image();
loadings[1].src = "images/game_loading2.png";
loadings[2] = new Image();
loadings[2].src = "images/game_loading3.png";
loadings[3] = new Image();
loadings[3].src = "images/game_loading4.png";
//2.2加载图片的数据
var LOADINGS = {
    imgs:loadings,
    length:loadings.length,
    width:186,
    height:38
}
//2.3加载运动图片的构造函数
function Loading(config){
    this.imgs = config.imgs;
    this.length = config.length;
    this.width = config.width;
    this.height = config.height;

    //定义一个访问数组汇中的索引
    this.startIndex = 0;//为0 从第一个开始访问
    //定义绘制图片的方法
    this.paint = function(){
        cxt.drawImage(this.imgs[this.startIndex],0,HEIGHT-this.height);
    }
    //定义一个速度 因为定时器的时间太短了
    this.time = 0;
    //定义运动方法
    this.step = function(){
        t
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值