• canvas 做一个小鸟运动的小游戏 (第一步)


    1. 首先有一个loadImage.js

        代码如下:

    function loadImage(imgUrl,fn){
    var imgObj = {};
    var tempImg,load = 0, imgLength = 0;
    for(var key in imgUrl){
    imgLength++;
    tempImg = new Image();
    tempImg.onload = function () {
    load++;
    if( load >= imgLength){
    fn( imgObj );
    }
    };

    tempImg.src = imgUrl[key];
    imgObj[key] = tempImg;
    }
    }

    2. 使画布开始动起来,也就是背景图
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <canvas id="cvs" height="500" width="500"></canvas>
    </body>
    <script src="js/loadImage.js"></script>
    <script>
    var cvs = document.getElementById("cvs");
    var ctx = cvs.getContext("2d");
    function Sky( ctx, img, speed) {
    //debugger;
    this.ctx = ctx;
    this.img = img;
    this.speed = speed || 2;
    /*创建一个实例,length就自增*/
    Sky.len++;
    console.log(Sky.len);
    this.width = this.img.width;
    //console.log(this.width);
    this.height = this.img.height;
    /*根据背景数量,动态计算起始的x轴坐标*/
    this.x = this.width * ( Sky.len - 1 );
    //console.log(this.x);
    //this.x = 0;
    this.y = 0;
    }
    /*sky实例默认的数量*/
    Sky.len = 0;
    /*给原型扩充方法*/
    Sky.prototype = {
    constructor: Sky,
    draw: function () {
    this.ctx.drawImage(this.img, this.x, this.y);
    }
    }
    </script>
    <script>
    loadImage({
    bird: './images/bird.png',
    land: './images/land.png',
    pipeDown: './images/pipeDown.png',
    pipeDown: './images/pipeDown.png',
    sky: './images/sky.png'
    },function ( imgObj) {

    /*根据背景的大小设置画布的大小*/
    cvs.width = imgObj.sky.width;
    cvs.height = imgObj.sky.height;

    var sky = new Sky(ctx, imgObj.sky,10);
    var sky2 = new Sky(ctx, imgObj.sky,10);
    setInterval(function () {
    sky.draw();
    sky.x -= sky.speed;
    //console.log(sky.x);
    if( Math.abs(sky.x) >= sky.width){
    sky.x += sky.width *2;
    }
    sky2.draw();
    sky2.x -= sky2.speed;
    if( Math.abs(sky2.x) >= sky2.width){
    sky2.x += sky2.width *2;
    }
    },100);
    })
    </script>
    </html>
    结果如图所示:(背景图片是运动的)




  • 相关阅读:
    python实现满二叉树递归循环
    二叉树遍历规则,先顺遍历/中序遍历/后序遍历
    满二叉树的循环递归
    python 中的super()继承,搜索广度为先
    UITableview 中获取非选中的cell
    iOS——UIButton响应传参数
    iOS- iPad UIPopoverController
    IPAD之分割视图 SplitViewController
    IOS7 隐藏状态栏
    iOS 强制横屏
  • 原文地址:https://www.cnblogs.com/huqinqin/p/7543757.html
Copyright © 2020-2023  润新知