canvas是一个可以让我们使用脚本绘图的标签betw

[Canvas前端游戏开采]——FlappyBird详解

2016/01/03 · HTML5 · Canvas

初稿出处: xingoo   

直接想本身做点小东西,直到方今看了本《HTML5游玩支付》,才打听游戏支付中的一丢丢入门知识。

本篇就针对学习的多少个样例,自身入手施行,做了个FlappyBird,源码分享在度盘 ;也足以参照他事他说加以考察github,里面有更多的娱乐样例。

canvas 制作flappy bird(像素小鸟)全流程,canvasflappy

想必英特网早已有多少个flappy-bird的html5版本啦,到这年flappy-bird大概也绝非前边那么火了,不过作为多少个菜鸟,本人想想,自身入手写二个flappy-bird的demo照旧很有成就感的。

canvas是贰个足以让大家选用脚本绘图的竹签,它提供了一多级完整的习性和方法。我们得以借此来贯彻图形绘制,图像管理依然达成简单的动画和玩耍制作。

行使JavaScript+canvas完毕图片裁剪,javascriptcanvas

canvas是一个得以让我们运用脚本绘图的价签,它提供了一层层完整的性情和方式。大家能够借此来落实图形绘制,图像管理仍然达成轻松的卡通和玩耍制作。

canvas标签独有两脾个性:width和height,用来设定画布的宽和高,若无通过标签属性大概脚本来设置,默以为300*150;

好了,canvas的牵线就先到此处,下边我们来会见javascript结合canvas达成图片的剪裁代码:

复制代码 代码如下:

var selectObj = null;
function ImageCrop(canvasId, imageSource, x, y, width, height) {
    var canvas = $("#" + canvasId);
    if (canvas.length == 0 && imageSource) {
        return;
    }
    function canvasMouseDown(e) {
        StopSelect(e);
        canvas.css("cursor", "default");
    }
    function canvasMouseMove(e) {
        var canvasOffset = canvas.offset();
        var pageX = e.pageX || event.targetTouches[0].pageX;
        var pageY = e.pageY || event.targetTouches[0].pageY;
        iMouseX = Math.floor(pageX - canvasOffset.left);
        iMouseY = Math.floor(pageY - canvasOffset.top);
        canvas.css("cursor", "default");
        if (selectObj.bDragAll) {
            canvas.css("cursor", "move");
            canvas.data("drag", true);
            var cx = iMouseX - selectObj.px;
            cx = cx < 0 ? 0 : cx;
            mx = ctx.canvas.width - selectObj.w;
            cx = cx > mx ? mx : cx;
            selectObj.x = cx;
            var cy = iMouseY - selectObj.py;
            cy = cy < 0 ? 0 : cy;
            my = ctx.canvas.height - selectObj.h;
            cy = cy > my ? my : cy;
            selectObj.y = cy;
        }
        for (var i = 0; i < 4; i++) {
            selectObj.bHow[i] = false;
            selectObj.iCSize[i] = selectObj.csize;
        }
        // hovering over resize cubes
        if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh &&
            iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[0] = true;
            selectObj.iCSize[0] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh &&
            iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[1] = true;
            selectObj.iCSize[1] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh &&
            iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[2] = true;
            selectObj.iCSize[2] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh &&
            iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[3] = true;
            selectObj.iCSize[3] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x && iMouseX < selectObj.x + selectObj.w && iMouseY > selectObj.y && iMouseY < selectObj.y + selectObj.h) {
            canvas.css("cursor", "move");
        }
        // in case of dragging of resize cubes
        var iFW, iFH, iFX, iFY, mx, my;
        if (selectObj.bDrag[0]) {
            iFX = iMouseX - selectObj.px;
            iFY = iMouseY - selectObj.py;
            iFW = selectObj.w + selectObj.x - iFX;
            iFH = selectObj.h + selectObj.y - iFY;
            canvas.data("drag", true);
        }
        if (selectObj.bDrag[1]) {
            iFX = selectObj.x;
            iFY = iMouseY - selectObj.py;
            iFW = iMouseX - selectObj.px - iFX;
            iFH = selectObj.h + selectObj.y - iFY;
            canvas.data("drag", true);
        }
        if (selectObj.bDrag[2]) {
            iFX = selectObj.x;
            iFY = selectObj.y;
            iFW = iMouseX - selectObj.px - iFX;
            iFH = iMouseY - selectObj.py - iFY;
            canvas.data("drag", true);
        }
        if (selectObj.bDrag[3]) {
            iFX = iMouseX - selectObj.px;
            iFY = selectObj.y;
            iFW = selectObj.w + selectObj.x - iFX;
            iFH = iMouseY - selectObj.py - iFY;
            canvas.data("drag", true);
        }
        if (iFW > selectObj.csizeh * 2 && iFH > selectObj.csizeh * 2) {
            selectObj.w = iFW;
            selectObj.h = iFH;
            selectObj.x = iFX;
            selectObj.y = iFY;
        }
        drawScene();
    }
    function canvasMouseOut() {
        $(canvas).trigger("mouseup");
    }
    function canvasMouseUp() {
        selectObj.bDragAll = false;
        for (var i = 0; i < 4; i++) {
            selectObj.bDrag[i] = false;
        }
        canvas.css("cursor", "default");
        canvas.data("select", {
            x: selectObj.x,
            y: selectObj.y,
            w: selectObj.w,
            h: selectObj.h
        });
        selectObj.px = 0;
        selectObj.py = 0;
    }
    function Selection(x, y, w, h) {
        this.x = x; // initial positions
        this.y = y;
        this.w = w; // and size
        this.h = h;
        this.px = x; // extra variables to dragging calculations
        this.py = y;
        this.csize = 4; // resize cubes size
        this.csizeh = 6; // resize cubes size (on hover)
        this.bHow = [false, false, false, false]; // hover statuses
        this.iCSize = [this.csize, this.csize, this.csize, this.csize]; // resize cubes sizes
        this.bDrag = [false, false, false, false]; // drag statuses
        this.bDragAll = false; // drag whole selection
    }
    Selection.prototype.draw = function () {
        ctx.strokeStyle = '#666';
        ctx.lineWidth = 2;
        ctx.strokeRect(this.x, this.y, this.w, this.h);
        // draw part of original image
        if (this.w > 0 && this.h > 0) {
            ctx.drawImage(image, this.x, this.y, this.w, this.h, this.x, this.y, this.w, this.h);
        }
        // draw resize cubes
        ctx.fillStyle = '#999';
        ctx.fillRect(this.x - this.iCSize[0], this.y - this.iCSize[0], this.iCSize[0] * 2, this.iCSize[0] * 2);
        ctx.fillRect(this.x + this.w - this.iCSize[1], this.y - this.iCSize[1], this.iCSize[1] * 2, this.iCSize[1] * 2);
        ctx.fillRect(this.x + this.w - this.iCSize[2], this.y + this.h

  • this.iCSize[2], this.iCSize[2] * 2, this.iCSize[2] * 2);
            ctx.fillRect(this.x - this.iCSize[3], this.y + this.h - this.iCSize[3], this.iCSize[3] * 2, this.iCSize[3] * 2);
        };
        var drawScene = function () {
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // clear canvas
            // draw source image
            ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
            // and make it darker
            ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
            ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            // draw selection
            selectObj.draw();
            canvas.mousedown(canvasMouseDown);
            canvas.on("touchstart", canvasMouseDown);
        };
        var createSelection = function (x, y, width, height) {
            var content = $("#imagePreview");
            x = x || Math.ceil((content.width() - width) / 2);
            y = y || Math.ceil((content.height() - height) / 2);
            return new Selection(x, y, width, height);
        };
        var ctx = canvas[0].getContext("2d");
        var iMouseX = 1;
        var iMouseY = 1;
        var image = new Image();
        image.onload = function () {
            selectObj = createSelection(x, y, width, height);
            canvas.data("select", {
                x: selectObj.x,
                y: selectObj.y,
                w: selectObj.w,
                h: selectObj.h
            });
            drawScene();
        };
        image.src = imageSource;
        canvas.mousemove(canvasMouseMove);
        canvas.on("touchmove", canvasMouseMove);
        var StopSelect = function (e) {
            var canvasOffset = $(canvas).offset();
            var pageX = e.pageX || event.targetTouches[0].pageX;
            var pageY = e.pageY || event.targetTouches[0].pageY;
            iMouseX = Math.floor(pageX - canvasOffset.left);
            iMouseY = Math.floor(pageY - canvasOffset.top);
            selectObj.px = iMouseX - selectObj.x;
            selectObj.py = iMouseY - selectObj.y;
            if (selectObj.bHow[0]) {
                selectObj.px = iMouseX - selectObj.x;
                selectObj.py = iMouseY - selectObj.y;
            }
            if (selectObj.bHow[1]) {
                selectObj.px = iMouseX - selectObj.x - selectObj.w;
                selectObj.py = iMouseY - selectObj.y;
            }
            if (selectObj.bHow[2]) {
                selectObj.px = iMouseX - selectObj.x - selectObj.w;
                selectObj.py = iMouseY - selectObj.y - selectObj.h;
            }
            if (selectObj.bHow[3]) {
                selectObj.px = iMouseX - selectObj.x;
                selectObj.py = iMouseY - selectObj.y - selectObj.h;
            }
            if (iMouseX > selectObj.x + selectObj.csizeh &&
                iMouseX < selectObj.x + selectObj.w - selectObj.csizeh &&
                iMouseY > selectObj.y + selectObj.csizeh &&
                iMouseY < selectObj.y + selectObj.h - selectObj.csizeh) {
                selectObj.bDragAll = true;
            }
            for (var i = 0; i < 4; i++) {
                if (selectObj.bHow[i]) {
                    selectObj.bDrag[i] = true;
                }
            }
        };
        canvas.mouseout(canvasMouseOut);
        canvas.mouseup(canvasMouseUp);
        canvas.on("touchend", canvasMouseUp);
        this.getImageData = function (previewID) {
            var tmpCanvas = $("<canvas></canvas>")[0];
            var tmpCtx = tmpCanvas.getContext("2d");
            if (tmpCanvas && selectObj) {
                tmpCanvas.width = selectObj.w;
                tmpCanvas.height = selectObj.h;
                tmpCtx.drawImage(image, selectObj.x, selectObj.y, selectObj.w, selectObj.h, 0, 0, selectObj.w, selectObj.h);
                if (document.getElementById(previewID)) {
                    document.getElementById(previewID).src = tmpCanvas.toDataURL();
                    document.getElementById(previewID).style.border = "1px solid #ccc";
                }
                return tmpCanvas.toDataURL();
            }
        };
    }
    function autoResizeImage(maxWidth, maxHeight, objImg) {
        var img = new Image();
        img.src = objImg.src;
        var hRatio;
        var wRatio;
        var ratio = 1;
        var w = objImg.width;
        var h = objImg.height;
        wRatio = maxWidth / w;
        hRatio = maxHeight / h;
        if (w < maxWidth && h < maxHeight) {
            return;
        }
        if (maxWidth == 0 && maxHeight == 0) {
            ratio = 1;
        } else if (maxWidth == 0) {
            if (hRatio < 1) {
                ratio = hRatio;
            }
        } else if (maxHeight == 0) {
            if (wRatio < 1) {
                ratio = wRatio;
            }
        } else if (wRatio < 1 || hRatio < 1) {
            ratio = (wRatio <= hRatio ? wRatio : hRatio);
        } else {
            ratio = (wRatio <= hRatio ? wRatio : hRatio) - Math.floor(wRatio <= hRatio ? wRatio : hRatio);
        }
        if (ratio < 1) {
            if (ratio < 0.5 && w < maxWidth && h < maxHeight) {
                ratio = 1 - ratio;
            }
            w = w * ratio;
            h = h * ratio;
        }
        objImg.height = h;
        objImg.width = w;
    }

同伙们拿去探索吧,希望大家能够欣赏,有问号就给自家留言吗。

canvas是二个方可让大家选拔脚本绘图的价签,它提供了一多级完整的习性和格局。大家得以借...

游玩截图

betway体育app 1

betway体育app 2

flappy bird制作全流程:

betway体育app 3

flappy-bird的html5版无非是由此canvas来画的,可能互连网也许有webgl版本的,不过本身一般没见过,要是您意识了,希望告知自身一声,我们一齐商量探讨。此前在微博上看看有大神用60几行就写出了多少个demo,那让自身写完事后发现本身的demo有将近200多行的代码,须臾间让本人对大神们三跪九叩的钦佩,当然作者的代码也足以轻松到几十行,可是那样写出来,不便于维护,对于新人也极难看懂。

canvas标签唯有两本天性:width和height,用来设定画布的宽和高,若无经过标签属性或然脚本来设置,默感到300*150;

HTML5之Canvas

Canvas是Html5中用于绘图的要素,它可以绘制种种图片,举例长方形,多边形,圆形等等。假设想要理解Canvas的选拔能够参见:

 

//假设想要使用canvas,首先须求获得上下文对象: ctx = document.getElementById('canvas').getContext('2d'); //然后使用那几个ctx绘制图形

1
2
3
//如果想要使用canvas,首先需要获得上下文对象:
ctx = document.getElementById('canvas').getContext('2d');
//然后使用这个ctx绘制图形

在cavas各种绘制都是单独的操作。比方下图的五个绘制图形,第贰个会以掩盖的花样绘制,因而绘图图形的次第就显示非凡第一了。

betway体育app 4

一、前言

像素小鸟这么些简单的玩乐于二零一四年在网络上爆红,游戏上线一段时间内appleStore上的下载量一度高达五千万次,风靡不常,

方今移动web的广泛为这么未有复杂逻辑和精密动画效果,可是野趣十足的小游戏提供了精粹的情形,

並且依据各大社交软件平台的传播效应,创新意识不断的小游戏有着精良的经营贩卖效益,获得了过多的关爱。

开始在网络查询了广大关于那么些小游戏的材质,但是基本上非常倒霉,本人的三结合有关学科将这么些游戏的至关重大框架整理出来,供大家一同念书。

html代码笔者就不写了,我们也都清楚,固然你连html代码也须求的话,那您接下去也就没须求看了,还不及直接跳转到w3school.com.cn。

好了,canvas的介绍就先到此处,上面我们来探问javascript结合canvas完毕图片的剪裁代码:

canvas之drawImage()

本篇的娱乐支付中,主要行使的是基于图片绘制的api:drawImage(),它有五个大旨的利用方法:

ctx.drawImage(image,this.bx,this.by,this.bwidth,this.bheight); ctx.drawImage(image,x,y,width,height,this.px,this.py,this.pwidth,this.pheight);

1
2
ctx.drawImage(image,this.bx,this.by,this.bwidth,this.bheight);
ctx.drawImage(image,x,y,width,height,this.px,this.py,this.pwidth,this.pheight);

率先个api中,钦赐Image对象,然后给出绘制图片的x,y坐标以及宽度和冲天就能够。

第一个api中,第一组x,y,width,height则内定了裁剪图片的坐标尺寸,那在行使多成分的矢量图时很常用。比如:

betway体育app 5

地点的图纸中为了减小图片能源的央求数量,把多数的因素放在了贰个图片中,此时就需求经过裁剪的主意,获取钦定的图片成分。

二、手艺中央

 基本JavaScript基础 ,canvas 基础, 面向对象的思量;

接下去就是珍视的js了,至于css吗?你明白的css对于canvas是无效的,那我干嘛还写css呢,那不是浪费生命啊

复制代码 代码如下:

FlappyBird原理解析

实则那些游戏很简短,一张图就能够看懂在那之中的神妙:

betway体育app 6

其间背景和本地是不动的。

鸟儿唯有上和下多少个动作,可以经过操纵小鸟的y坐标实现。

内外的管敬仲只会向左移动,为了轻便达成,游戏中多个镜头仅仅会产出一些管敬仲,那样当管仲移出右边的背景框,就自动把管仲放在最侧边!

if(up_pipe.px+up_pipe.pwidth>0){ up_pipe.px -= velocity; down_pipe.px -= velocity; }else{ up_pipe.px = 400; down_pipe.px = 400; up_pipe.pheight = 100+Math.random()*200; down_pipe.py = up_pipe.pheight+pipe_height; down_pipe.pheight = 600-down_pipe.py; isScore = true; }

1
2
3
4
5
6
7
8
9
10
11
if(up_pipe.px+up_pipe.pwidth>0){
                up_pipe.px -= velocity;
                down_pipe.px -= velocity;
            }else{
                up_pipe.px = 400;
                down_pipe.px = 400;
                up_pipe.pheight = 100+Math.random()*200;
                down_pipe.py = up_pipe.pheight+pipe_height;
                down_pipe.pheight = 600-down_pipe.py;
                isScore = true;
            }

很轻松吗!

鉴于该游戏一共就那多少个因素,因而把他们都放入四个Objects数组中,通过setInteral()方法,在早夜晚隔时间内,试行贰遍重绘

重绘的时候会先去掉画面中的全部因素,然后依据新的因素的坐标三回绘制图形,那样就能够现出活动的效力。

三、思路整理

一初步率先定义bird对象,建议用构造函数的秘技,当然你也足以用工厂函数,这没怎么关联的

var selectObj = null;
function ImageCrop(canvasId, imageSource, x, y, width, height) {
    var canvas = $("#" + canvasId);
    if (canvas.length == 0 && imageSource) {
        return;
    }
    function canvasMouseDown(e) {
        StopSelect(e);
        canvas.css("cursor", "default");
    }
    function canvasMouseMove(e) {
        var canvasOffset = canvas.offset();
        var pageX = e.pageX || event.targetTouches[0].pageX;
        var pageY = e.pageY || event.targetTouches[0].pageY;
        iMouseX = Math.floor(pageX - canvasOffset.left);
        iMouseY = Math.floor(pageY - canvasOffset.top);
        canvas.css("cursor", "default");
        if (selectObj.bDragAll) {
            canvas.css("cursor", "move");
            canvas.data("drag", true);
            var cx = iMouseX - selectObj.px;
            cx = cx < 0 ? 0 : cx;
            mx = ctx.canvas.width - selectObj.w;
            cx = cx > mx ? mx : cx;
            selectObj.x = cx;
            var cy = iMouseY - selectObj.py;
            cy = cy < 0 ? 0 : cy;
            my = ctx.canvas.height - selectObj.h;
            cy = cy > my ? my : cy;
            selectObj.y = cy;
        }
        for (var i = 0; i < 4; i++) {
            selectObj.bHow[i] = false;
            selectObj.iCSize[i] = selectObj.csize;
        }
        // hovering over resize cubes
        if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh &&
            iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[0] = true;
            selectObj.iCSize[0] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh &&
            iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[1] = true;
            selectObj.iCSize[1] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh &&
            iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[2] = true;
            selectObj.iCSize[2] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh &&
            iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) {
            canvas.css("cursor", "pointer");
            selectObj.bHow[3] = true;
            selectObj.iCSize[3] = selectObj.csizeh;
        }
        if (iMouseX > selectObj.x && iMouseX < selectObj.x + selectObj.w && iMouseY > selectObj.y && iMouseY < selectObj.y + selectObj.h) {
            canvas.css("cursor", "move");
        }
        // in case of dragging of resize cubes
        var iFW, iFH, iFX, iFY, mx, my;
        if (selectObj.bDrag[0]) {
            iFX = iMouseX - selectObj.px;
            iFY = iMouseY - selectObj.py;
            iFW = selectObj.w + selectObj.x - iFX;
            iFH = selectObj.h + selectObj.y - iFY;
            canvas.data("drag", true);
        }
        if (selectObj.bDrag[1]) {
            iFX = selectObj.x;
            iFY = iMouseY - selectObj.py;
            iFW = iMouseX - selectObj.px - iFX;
            iFH = selectObj.h + selectObj.y - iFY;
            canvas.data("drag", true);
        }
        if (selectObj.bDrag[2]) {
            iFX = selectObj.x;
            iFY = selectObj.y;
            iFW = iMouseX - selectObj.px - iFX;
            iFH = iMouseY - selectObj.py - iFY;
            canvas.data("drag", true);
        }
        if (selectObj.bDrag[3]) {
            iFX = iMouseX - selectObj.px;
            iFY = selectObj.y;
            iFW = selectObj.w + selectObj.x - iFX;
            iFH = iMouseY - selectObj.py - iFY;
            canvas.data("drag", true);
        }
        if (iFW > selectObj.csizeh * 2 && iFH > selectObj.csizeh * 2) {
            selectObj.w = iFW;
            selectObj.h = iFH;
            selectObj.x = iFX;
            selectObj.y = iFY;
        }
        drawScene();
    }
    function canvasMouseOut() {
        $(canvas).trigger("mouseup");
    }
    function canvasMouseUp() {
        selectObj.bDragAll = false;
        for (var i = 0; i < 4; i++) {
            selectObj.bDrag[i] = false;
        }
        canvas.css("cursor", "default");
        canvas.data("select", {
            x: selectObj.x,
            y: selectObj.y,
            w: selectObj.w,
            h: selectObj.h
        });
        selectObj.px = 0;
        selectObj.py = 0;
    }
    function Selection(x, y, w, h) {
        this.x = x; // initial positions
        this.y = y;
        this.w = w; // and size
        this.h = h;
        this.px = x; // extra variables to dragging calculations
        this.py = y;
        this.csize = 4; // resize cubes size
        this.csizeh = 6; // resize cubes size (on hover)
        this.bHow = [false, false, false, false]; // hover statuses
        this.iCSize = [this.csize, this.csize, this.csize, this.csize]; // resize cubes sizes
        this.bDrag = [false, false, false, false]; // drag statuses
        this.bDragAll = false; // drag whole selection
    }
    Selection.prototype.draw = function () {
        ctx.strokeStyle = '#666';
        ctx.lineWidth = 2;
        ctx.strokeRect(this.x, this.y, this.w, this.h);
        // draw part of original image
        if (this.w > 0 && this.h > 0) {
            ctx.drawImage(image, this.x, this.y, this.w, this.h, this.x, this.y, this.w, this.h);
        }
        // draw resize cubes
        ctx.fillStyle = '#999';
        ctx.fillRect(this.x - this.iCSize[0], this.y - this.iCSize[0], this.iCSize[0] * 2, this.iCSize[0] * 2);
        ctx.fillRect(this.x + this.w - this.iCSize[1], this.y - this.iCSize[1], this.iCSize[1] * 2, this.iCSize[1] * 2);
        ctx.fillRect(this.x + this.w - this.iCSize[2], this.y + this.h

仿照小鸟重力

鉴于那一个娱乐不关乎小鸟横向的位移,由此假使模拟出小鸟下跌的动作以及上涨的动作就足以了。

betway体育app 7

上升:那几个很简短,只要把小鸟的y坐标减去料定的值就足以了

下落:其实重力无需运用gt^2来效仿,能够差非常的少的钦赐多个变量,v1和gravity,那四个变量与setInterval()中的时间共同功效,就会模仿重力。

ver2 = ver1+gravity; bird.by += (ver2+ver1)*0.5;

1
2
ver2 = ver1+gravity;
bird.by += (ver2+ver1)*0.5;

成套娱乐的逻辑比较轻巧:

首先游戏法规:鸟撞到管道上,地上要完蛋,飞到显示器外要完蛋。

其次:鸟在飞翔的进程中,会落下,类似落体运动,需求游戏者不断点击荧屏让鸟向上飞。

重复正是:鸟和背景成分的相对移动的进度,鸟不动,背景左移。

  1. var Bird = function (param) {  
  2.                 this.x = param.x || 0;  
  3.                 this.y = param.y || 0;  
  4.                 this.w = param.w;  
  5.                 this.h = param.h;  
  6.                 this.yDir = param.yDir || 1;  
  7.                 this.img = param.img;  
  8.   
  9.                 return this;  
  10.             }  
  • this.iCSize[2], this.iCSize[2] * 2, this.iCSize[2] * 2);
            ctx.fillRect(this.x - this.iCSize[3], this.y + this.h - this.iCSize[3], this.iCSize[3] * 2, this.iCSize[3] * 2);
        };
        var drawScene = function () {
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // clear canvas
            // draw source image
            ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
            // and make it darker
            ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
            ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            // draw selection
            selectObj.draw();
            canvas.mousedown(canvasMouseDown);
            canvas.on("touchstart", canvasMouseDown);
        };
        var createSelection = function (x, y, width, height) {
            var content = $("#imagePreview");
            x = x || Math.ceil((content.width() - width) / 2);
            y = y || Math.ceil((content.height() - height) / 2);
            return new Selection(x, y, width, height);
        };
        var ctx = canvas[0].getContext("2d");
        var iMouseX = 1;
        var iMouseY = 1;
        var image = new Image();
        image.onload = function () {
            selectObj = createSelection(x, y, width, height);
            canvas.data("select", {
                x: selectObj.x,
                y: selectObj.y,
                w: selectObj.w,
                h: selectObj.h
            });
            drawScene();
        };
        image.src = imageSource;
        canvas.mousemove(canvasMouseMove);
        canvas.on("touchmove", canvasMouseMove);
        var StopSelect = function (e) {
            var canvasOffset = $(canvas).offset();
            var pageX = e.pageX || event.targetTouches[0].pageX;
            var pageY = e.pageY || event.targetTouches[0].pageY;
            iMouseX = Math.floor(pageX - canvasOffset.left);
            iMouseY = Math.floor(pageY - canvasOffset.top);
            selectObj.px = iMouseX - selectObj.x;
            selectObj.py = iMouseY - selectObj.y;
            if (selectObj.bHow[0]) {
                selectObj.px = iMouseX - selectObj.x;
                selectObj.py = iMouseY - selectObj.y;
            }
            if (selectObj.bHow[1]) {
                selectObj.px = iMouseX - selectObj.x - selectObj.w;
                selectObj.py = iMouseY - selectObj.y;
            }
            if (selectObj.bHow[2]) {
                selectObj.px = iMouseX - selectObj.x - selectObj.w;
                selectObj.py = iMouseY - selectObj.y - selectObj.h;
            }
            if (selectObj.bHow[3]) {
                selectObj.px = iMouseX - selectObj.x;
                selectObj.py = iMouseY - selectObj.y - selectObj.h;
            }
            if (iMouseX > selectObj.x + selectObj.csizeh &&
                iMouseX < selectObj.x + selectObj.w - selectObj.csizeh &&
                iMouseY > selectObj.y + selectObj.csizeh &&
                iMouseY < selectObj.y + selectObj.h - selectObj.csizeh) {
                selectObj.bDragAll = true;
            }
            for (var i = 0; i < 4; i++) {
                if (selectObj.bHow[i]) {
                    selectObj.bDrag[i] = true;
                }
            }
        };
        canvas.mouseout(canvasMouseOut);
        canvas.mouseup(canvasMouseUp);
        canvas.on("touchend", canvasMouseUp);
        this.getImageData = function (previewID) {
            var tmpCanvas = $("<canvas></canvas>")[0];
            var tmpCtx = tmpCanvas.getContext("2d");
            if (tmpCanvas && selectObj) {
                tmpCanvas.width = selectObj.w;
                tmpCanvas.height = selectObj.h;
                tmpCtx.drawImage(image, selectObj.x, selectObj.y, selectObj.w, selectObj.h, 0, 0, selectObj.w, selectObj.h);
                if (document.getElementById(previewID)) {
                    document.getElementById(previewID).src = tmpCanvas.toDataURL();
                    document.getElementById(previewID).style.border = "1px solid #ccc";
                }
                return tmpCanvas.toDataURL();
            }
        };
    }
    function autoResizeImage(maxWidth, maxHeight, objImg) {
        var img = new Image();
        img.src = objImg.src;
        var hRatio;
        var wRatio;
        var ratio = 1;
        var w = objImg.width;
        var h = objImg.height;
        wRatio = maxWidth / w;
        hRatio = maxHeight / h;
        if (w < maxWidth && h < maxHeight) {
            return;
        }
        if (maxWidth == 0 && maxHeight == 0) {
            ratio = 1;
        } else if (maxWidth == 0) {
            if (hRatio < 1) {
                ratio = hRatio;
            }
        } else if (maxHeight == 0) {
            if (wRatio < 1) {
                ratio = wRatio;
            }
        } else if (wRatio < 1 || hRatio < 1) {
            ratio = (wRatio <= hRatio ? wRatio : hRatio);
        } else {
            ratio = (wRatio <= hRatio ? wRatio : hRatio) - Math.floor(wRatio <= hRatio ? wRatio : hRatio);
        }
        if (ratio < 1) {
            if (ratio < 0.5 && w < maxWidth && h < maxHeight) {
                ratio = 1 - ratio;
            }
            w = w * ratio;
            h = h * ratio;
        }
        objImg.height = h;
        objImg.width = w;
    }

碰撞检查评定

娱乐中型小型鸟遇到管敬仲或许本地都会算游戏截至:

betway体育app 8

其中条件1上管道的检查实验为:

((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&(bird.by<up_pipe.py+up_pipe.pheight))|| ((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&(bird.by<up_pipe.py+up_pipe.pheight))

1
2
((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&(bird.by<up_pipe.py+up_pipe.pheight))||
((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&(bird.by<up_pipe.py+up_pipe.pheight))

条件2下管道的检查评定为:

((bird.bx>down_pipe.px)&&(bird.by>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by<down_pipe.py+down_pipe.pheight))|| ((bird.bx>down_pipe.px)&&(bird.by+bird.bheight>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by+bird.bheight<down_pipe.py+down_pipe.pheight))

1
2
((bird.bx>down_pipe.px)&&(bird.by>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by<down_pipe.py+down_pipe.pheight))||
((bird.bx>down_pipe.px)&&(bird.by+bird.bheight>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by+bird.bheight<down_pipe.py+down_pipe.pheight))

条件3地面的检验最简便,为:

bird.by+bird.bheight>ground.bgy

1
bird.by+bird.bheight>ground.bgy

比方满意那多个标准,固然游戏结束,会去掉循环以及提示游戏结束音信。

将总体游戏细化:

咱俩应用面向对象的思绪来制作,具体的事物用构造函数来创制,方法放到构造函数的本来面目对象中。

游戏细化那几个进度不是轻便的,若是在并未有有关指引的情景下,自个儿要持续的构成自身的主张去试错。

本身使用的艺术是选择Xmind将流程以脑图的样式绘制下来,分块去做,不断细化记录本身的思路,最终表现的作用如下:

(顺序依据图片中的序号去看  脑图、素材、及整体源码下载地址: 想演练的校友能够点这里)

脑图分为三大块:1、准备阶段 2、主函数 3、游戏优化。

betway体育app 9

betway体育app 10

 

 

创制叁个bird的构造函数,传入参数param 并赶回this,参数param是荣辱与共的安顿参数。

同伴们拿去试试啊,希望大家能够喜欢,格外就给自己留言呢。

分数总结

分数的测算与碰撞检查评定类似,设置叁个开关,当管仲重新出现时,设置为true。当分值加1时,设置为false。

鸟类的最左侧的x坐标假如过量了管仲的x+width,就以为成功通过。

if(isScore && bird.bx>up_pipe.px+up_pipe.pwidth){ score += 1; isScore = false; if(score>0 && score%10 === 0){ velocity++; } }

1
2
3
4
5
6
7
if(isScore && bird.bx>up_pipe.px+up_pipe.pwidth){
                score += 1;
                isScore = false;
                if(score>0 && score%10 === 0){
                    velocity++;
                }
            }

通过后,分值加1,速度+1。

 四、游戏完结:

如今整合脑图来渐渐落到实处大家的游艺。

1.装置canvas画布,绸缪图片数据,当图片加载成功后实行回调函数;

betway体育app 11<canvas id="cvs" width="800" height="600"></canvas> <script> var imglist = [ { "name":"birds","src":"res/birds.png"}, { "name":"land","src":"res/land.png"}, { "name":"pipe1","src":"res/pipe1.png"}, { "name":"pipe2","src":"res/pipe2.png"}, { "name":"sky","src":"res/sky.png"} ]; var cvs = document.getElementById("cvs"); var ctx = cvs.getContext("2d"); </script> 画布希图,图片数据筹算

那边这一个入口函数的安装要当心,必需保险图片能源加载成功后再实行其余操作,每加载一张图片我们让imgCount--,减到0的时候再施行主函数;

betway体育app 12function load (source, callback ){ var imgEls={}; var imgCount=source.length; for (var i = 0; i < imgCount; i++) { var name = source[i].name; var newImg = new Image (); newImg.src = source[i].src; imgEls[name] = newImg; imgEls[name].add伊夫ntListener("load",function(){ imgCount--; if(imgCount==0){ callback(imgEls); }; }) }; }; 入口函数设置

主循环的安装:这里大家不使用setInterval来决定循环次数,大家应用一个叫requestAnimationFrame()的计时器

       因为setInterval会时有产生时间标称误差,setInterval只可以依赖时间来移动固定距离。

       那对于轮播图一类几千飞秒切换壹次的动作来说并从未什么样关系,不过对于大家16-18阿秒绘制一回的卡通是那二个不正确的;

       requestAnimationFrame()那个机械漏刻的补益是依照浏览器的个性来推行叁个函数,大家用来收获五回绘制的间隔时间;

       移动距离的计量改换成速度×间隔时间的艺术,来化解绘图不标准的主题素材。

betway体育app 13var preTime= Date.now(); //获取当前时间 function run(){ var now = Date.now(); //获取最新时刻 dt = now - preTime; //获取时间距离 preTime = now; //更新当前光阴 ctx.clearRect(0,0,800,600); //清空画布 //--------------------------------------------- 绘制代码推行区域 //----------------------------------------------- requestAnimationFrame(run); //再次奉行run函数 } requestAnimationFrame(run); //第贰回试行run函数; 设置绘制格局

2、主函数分为两片段功能,简单说就是把图画上去,然后管理动态效果,再剖断一下是还是不是违犯禁令。

2.1 小鸟的绘图:

  小鸟本人有一个双翅扇动的效率,和四个下跌的经过。

  双翅扇动的进度是一张Smart图三幅画面包车型地铁的切换(设置多少个index属性,调整Smart图的岗位),下跌过程是其y坐标在画布上的移位();

  所以小鸟的构造函数中应当包含(图源,x坐标,y坐标,速度,下降加速度,ctx(context画布))等参数。

  这里需求专心几点:

  •  小鸟的绘图选用canvas drawImage的九参数情势(分别是图片,原图的裁切源点,原图的宽高,贴到画布上的职位,贴到画布上的宽高);
  •  小鸟的羽翼扇动不能够太快,所以大家设置八个阀门函数,当累计计时抢先100ms的时候切换一下图形,然后在让一齐计时减去100ms;
  •  小鸟的裁减要求利用一定物理知识,但是都非常粗大略啦。 大家都以经过速度×时间来完毕;

betway体育app 14var Bird= function (img,x,y,speed,a,ctx){ this.img = img; this.x = x; this.y = y; this.speed = speed; this.a =a ; this.ctx = ctx; this.index = 0; //用于营造小鸟扇双翅的动作 } 伯德.prototype.draw = function (){ this.ctx.drawImage( this.img,52*this.index,0,52,45, this.x,this.y,52,45 ) } var durgather=0; 伯德.prototype.update = function(dur){ //小鸟羽翼扇动每100ms切换一张图纸 durgather+=dur; if(durgather>100){ this.index++; if(this.index===2){ this.index=0; } durgather -= 100; } //小鸟下跌动作 this.speed = this.speed + this.a *dur; this.y = this.y + this.speed * dur; } 小鸟的构造函数及动作调整

  构造二个鸟类,並且将其动作刷新函数和制图函数放置在我们地点提到的绘图区域,此后结构出的附近对象都以这么的操作步骤:

  这里要求细心的一点是,怎样让鸟儿顺畅的上进飞翔,其实照旧情理知识,由于加速度的功力,大家给小鸟叁个提升的顺时速度就能够了。

betway体育app 15load(imglist ,function(imgEls){ //创造对象 //在主函数中开创贰个小鸟 var bird = new Bird(imgEls["birds"],150,100,0.0003,0.0006,ctx); //主循环 var preTime= Date.now(); function run(){ var now = Date.now(); dt = now - preTime; preTime = now; ctx.clearRect(0,0,800,600); //--------图片绘制区域------- bird.update(dt) bird.draw(); //------------------------- requestAnimationFrame(run); } requestAnimationFrame(run); //设置点击事件。给小鸟三个一眨眼的腾赶快度 cvs.addEventListener("click",function(){ bird.speed = -0.3; } ) }) 绘制小鸟,点击小鸟上海飞机创设厂

成效如下:

betway体育app 16

2.2天幕的绘图:

  天空的绘图相比轻松了,只要采用canvas drawImage的三参数情势就可以(图源,画布上的坐标)。

  这里独一专一的某个是,无缝滚动的达成,对于800*600分辨率这种状态大家创立五个天空对象就可以了,可是为了适配更加多的意况,咱们将那些效用写活

  在天宇的构造函数上加叁个count属性设置多少个天空图片,count属性让实例通过原形中的方法采访。后边涉及到重现的地头和管道,都给它们拉长这种思量。

betway体育app 17var Sky = function(img,x,speed,ctx) { this.img = img ; this.ctx = ctx; this.x = x; this.speed = speed; } Sky.prototype.draw = function(){ this.ctx.drawImage( this.img ,this.x,0 ) } Sky.prototype.setCount = function(count){ Sky.count = count; } Sky.prototype.update = function(dur){ this.x = this.x+ this.speed * dur; if(this.x<-800){ //天空图片的大幅是800 this.x = Sky.count * 800 + this.x; //当向左移动了一整张图片后立即切回第一张图片 } } 天空构造函数及移动函数

  同理在主函数中开创2个天空对象,并将立异函数和制图函数放置在主循环的绘图区域;

  setcount是用来安装无缝滚动的

  注意一点:绘制上的图片是有一个层级关系的,无法把鸟画到天空的上面,那自然最后画鸟了,上面涉及到的覆盖难点不再特意提到。

  这里仅插入部分连锁代码

betway体育app 18var bird = new Bird(imgEls["birds"],150,100,0.0003,0.0006,ctx); var sky1 = new Sky(imgEls["sky"],0,-0.3,ctx); var sky2 = new Sky(imgEls["sky"],800,-0.3,ctx); //主循环 var preTime= Date.now(); function run(){ var now = Date.now(); dt = now - preTime; preTime = now; ctx.clearRect(0,0,800,600); //--------图片绘制区域------- sky1.update(dt); sky1.draw() sky2.update(dt); sky2.draw() sky1.setCount(2); bird.update(dt) bird.draw(); //------------------------- 绘制天空

2.3 地面包车型客车绘图

  和天上的绘图完全平等,由于本地图片尺寸很小,所以我们要多画多少个

betway体育app 19var Land = function(img,x,speed,ctx){ this.img = img ; this.x = x; this.speed = speed; this.ctx = ctx ; } Land.prototype.draw = function(){ this.ctx.drawImage ( this.img , this.x ,488 ) } Land.prototype.setCount= function(count){ Land.count = count; } Land.prototype.update = function(dur){ this.x = this.x + this.speed * dur; if (this.x <- 336){ this.x = this.x + Land.count * 336; //无缝滚动的兑现 } } 地面包车型客车构造函数及运动函数 betway体育app 20//创立----放置在开创区域 var land1 = new Land(imgEls["land"],0,-0.3,ctx); var land2 = new Land(imgEls["land"],336*1,-0.3,ctx); var land3 = new Land(imgEls["land"],336*2,-0.3,ctx); var land4 = new Land(imgEls["land"],336*3,-0.3,ctx); //绘制 ----放置在绘制区域 land1.update(dt); land1.draw(); land2.update(dt); land2.draw(); land3.update(dt); land3.draw(); land4.update(dt); land4.draw(); land1.setCount(4); //设置无缝滚动 绘制地面重要代码

2.4绘制管道

  管道的绘图有三个难处是管道中度的规定

  要点:

  •  为了保险游戏可玩性,管道必需有贰个定位中度+三个随机中度,且上下管道之间的留白是定点的增加率。
  • 管道不是连接的,七个相邻的管道之间有距离
  • 留神管道在无缝播放,抽回后必得交给贰个新的即兴中度,给客商一种错觉,感觉又多少个管道飘了过来。

  

betway体育app 21var Pipe = function(upImg,downImg,x,speed,ctx){ this.x = x; this.upImg = upImg ; this.downImg = downImg; this.speed = speed; this.ctx = ctx; this.r = Math.random() *200 + 100; //随机中度+固定高度 } Pipe.prototype.draw = function(){ this.ctx.drawImage( this.upImg, this.x , this.r - 420 //管道图纸的长短是420 ) this.ctx.drawImage( this.downImg, this.x , this.r +150 //管道中国建工业总会公司的留白是150px ) } Pipe.prototype.setCount = function( count,gap ){ Pipe.count = count; Pipe.gap = gap; //这里是此次绘制的特别之处,参加了距离 } Pipe.prototype.update =function( dur ){ this.x = this.x + this.speed*dur; if(this.x <- 52){ //管道宽度52px this.x = this.x + Pipe.count * Pipe.gap; //无缝滚动 this.r = Math.random() *200 + 150; //切换后的管道必得另行安装一个中度,给客户叁个新管道的错觉 } } 管道的构造函数及运动函数 betway体育app 22//创设区域 var pipe1 = new Pipe(imgEls["pipe2"],imgEls["pipe1"],400, -0.1,ctx); var pipe2 = new Pipe(imgEls["pipe2"],imgEls["pipe1"],600, -0.1,ctx); var pipe3 = new Pipe(imgEls["pipe2"],imgEls["pipe1"],800, -0.1,ctx); var pipe4 = new Pipe(imgEls["pipe2"],imgEls["pipe1"],1000,-0.1,ctx); var pipe5 = new Pipe(imgEls["pipe2"],imgEls["pipe1"],1200,-0.1,ctx); //绘制区域 pipe1.update(dt); pipe1.draw(); pipe2.update(dt); pipe2.draw(); pipe3.update(dt); pipe3.draw(); pipe4.update(dt); pipe4.draw(); pipe5.update(dt); pipe5.draw(); pipe1.setCount(5,200); //设置管道数量和距离 管道的绘图主要代码

到这一步我们的要害画面就制作出来了,是否很简短呢O(∩_∩)O~

2.5 决断游戏是还是不是违犯禁令

betway体育app 23 //大家更换一下主循环,设置多个gameover为false来调节函数的实行//任何违法都会触发gameover=true; var gameover = false; if(bird.y < 0 || bird.y > 488 -45/2 ){ //遭受天和地 gameover = true ; } if(!gameover){ //若无终结游戏则持续玩乐 requestAnimationFrame(run); } 轻易判读gameover

  2. 相见管道甘休游戏

betway体育app 24//x和y到时候大家传入小鸟的移动轨迹,每便重绘管道都有咬定 Pipe.prototype.hitTest = function(x,y){ return (x > this.x && x < this.x + 52) //在管仲横向中间 &&(! (y >this.r && y < this.r +150)); //在管敬仲竖向中间 } 判定是或不是蒙受管子 betway体育app 25 var gameover = false; gameover = gameover || pipe1.hitTest(bird.x ,bird.y); gameover = gameover || pipe2.hitTest(bird.x ,bird.y); gameover = gameover || pipe3.hitTest(bird.x ,bird.y); gameover = gameover || pipe4.hitTest(bird.x ,bird.y); gameover = gameover || pipe5.hitTest(bird.x ,bird.y); //逻辑终端 if(bird.y < 0 || bird.y > 488 -45/2 ){ gameover = true ; } if(!gameover){ requestAnimationFrame(run); } 主循环的论断标准构成

betway体育app 26

到这一步大家的嬉戏达成的比较多了,剩下的正是某些数指标考订

根本须求订正的多个点是碰上的谋算,因为大家具有的撞击都是遵照小鸟图片的左上角总计的,那样就能够有不标准的难题,通过测验很轻巧将以此距离加减校对了

 

3.游戏的优化

 小鸟游戏的鸟类在上下的长河中会随着点击,抬头飞翔,或退让冲刺,如何是好到那些效应啊?

 答案正是活动canvas 坐标系和抉择坐标系的角度  ctx.translate()和ctx.rotate();

 为了防止全部坐标系的欧洲经济共同体旋转运动

 供给在小鸟绘制函数伯德.prototype.draw里前边后端参预ctx.save() 和ctx.restore()来单独主宰小鸟画布

betway体育app 27Bird.prototype.draw = function (){ this.ctx.save(); this.ctx.translate(this.x ,this.y); //坐标移动到小鸟的核心点上 this.ctx.rotate((Math.PI /6) * this.speed / 0.3 ); //小鸟最大旋转30度,并趁机速度实时更换角度 this.ctx.drawImage( this.img,52*this.index,0,52,45, -52/2,-45/2,52,45 //这里非常重大的一些是,整个小鸟坐标系开端运动 ) this.ctx.restore(); } 参预小鸟旋转效果

本来最终不要遗忘对管道碰撞的剖断,在此间再改良贰遍。

实际要是希图进入旋转效果,上一次的勘误无需,你会发觉众多种复工。

最后做出的功力如下:

betway体育app 28

 主体功能和逻辑已经整整落到实处。越多的效应可以自行增添。

 如若想和煦练习一下,请点击游戏细化部分的链接下载相关资料和任何源码。

制作flappy bird(像素小鸟)全流程,canvasflappy flappy bird制作全流程: 一、前言 像素小鸟这一个轻便的玩耍于二〇一四年在网络上爆红,游戏上...

 

你也许感兴趣的稿子:

  • js+html5绘制图片到canvas的章程
  • JS移动端/H5同有的时候候选用多张图纸上传并使用canvas压缩图片
  • js完结canvas保存图片为png格式并下载到本地的办法
  • Js利用Canvas完毕图片压缩作用
  • js实现canvas图片与img图片的并行转变的演示
  • JavaScript+html5 canvas完毕图片破碎重组动画特效
  • javascript结合canvas达成图片旋转效果
  • js HTML5 canvas绘制图片的法门
  • Canvas + JavaScript 制作图纸粒子效果
  • js canvas完成放大镜查看图片功用
  • JavaScript+Canvas完结彩色图片调换到黑白图片的法子剖析

全部源码

<!DOCTYPE html> <html> <head> <title>Flappy Bird</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> // Edit by xingoo // Fork on my github: var ctx; var cwidth = 400; var cheight = 600; var objects = []; var birdIndex = 0; var ver1 = 10; var ver2; var gravity = 2; var pipe_height = 200; var velocity = 10; var tid; var score = 0; var isScore = false; var birds = ["./images/0.gif","./images/1.gif","./images/2.gif"]; var back = new Background(0,0,400,600,"./images/bg.png"); var up_pipe = new UpPipe(0,0,100,200,"./images/pipe.png"); var down_pipe = new DownPipe(0,400,100,200,"./images/pipe.png"); var ground = new Background(0,550,400,200,"./images/ground.png"); var bird = new Bird(80,300,40,40,birds); objects.push(back); objects.push(up_pipe); objects.push(down_pipe); objects.push(ground); objects.push(bird); function UpPipe(x,y,width,height,img_src){ this.px = x; this.py = y; this.pwidth = width; this.pheight = height; this.img_src = img_src; this.draw = drawUpPipe; } function DownPipe(x,y,width,height,img_src){ this.px = x; this.py = y; this.pwidth = width; this.pheight = height; this.img_src = img_src; this.draw = drawDownPipe; } function drawUpPipe(){ var image = new Image(); image.src = this.img_src; ctx.drawImage(image,150,500,150,800,this.px,this.py,this.pwidth,this.pheight); } function drawDownPipe(){ var image = new Image(); image.src = this.img_src; ctx.drawImage(image,0,500,150,500,this.px,this.py,this.pwidth,this.pheight); } function Background(x,y,width,height,img_src){ this.bgx = x; this.bgy = y; this.bgwidth = width; this.bgheight = height; var image = new Image(); image.src = img_src; this.img = image; this.draw = drawbg; } function drawbg(){ ctx.drawImage(this.img,this.bgx,this.bgy,this.bgwidth,this.bgheight); } function Bird(x,y,width,height,img_srcs){ this.bx = x; this.by = y; this.bwidth = width; this.bheight = height; this.imgs = img_srcs; this.draw = drawbird; } function drawbird(){ birdIndex++; var image = new Image(); image.src = this.imgs[birdIndex%3]; ctx.drawImage(image,this.bx,this.by,this.bwidth,this.bheight); } function calculator(){ if(bird.by+bird.bheight>ground.bgy || ((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&( bird.by<up_pipe.py+up_pipe.pheight))|| ((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&( bird.by<up_pipe.py+up_pipe.pheight))|| ((bird.bx>down_pipe.px)&&(bird.by>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by<down_pipe.py+down_pipe.pheight))|| ((bird.bx>down_pipe.px)&&(bird.by+bird.bheight>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by+bird.bheight<down_pipe.py+down_pipe.pheight))){ clearInterval(tid); ctx.fillStyle = "rgb(255,255,255)"; ctx.font = "30px Accent"; ctx.fillText("You got "+score+"!",110,100) return; } ver2 = ver1+gravity; bird.by += (ver2+ver1)*0.5; if(up_pipe.px+up_pipe.pwidth>0){ up_pipe.px -= velocity; down_pipe.px -= velocity; }else{ up_pipe.px = 400; down_pipe.px = 400; up_pipe.pheight = 100+Math.random()*200; down_pipe.py = up_pipe.pheight+pipe_height; down_pipe.pheight = 600-down_pipe.py; isScore = true; } if(isScore && bird.bx>up_pipe.px+up_pipe.pwidth){ score += 1; isScore = false; if(score>0 && score%10 === 0){ velocity++; } } ctx.fillStyle = "rgb(255,255,255)"; ctx.font = "30px Accent"; if(score>0){ score%10!==0?ctx.fillText(score,180,100):ctx.fillText("Great!"+score,120,100); } } function drawall(){ ctx.clearRect(0,0,cwidth,cheight); var i; for(i=0;i<objects.length;i++){ objects[i].draw(); } calculator(); } function keyup(e){ var e = e||event; var currKey = e.keyCode||e.which||e.charCode; switch (currKey){ case 32: bird.by -= 80; break; } } function init(){ ctx = document.getElementById('canvas').getContext('2d'); document.onkeyup = keyup; drawall(); tid = setInterval(drawall,80); } </script> </head> <body onLoad="init();"> <canvas id="canvas" width="400" height="600" style="margin-left:200px;"> Your browser is not support canvas! </canvas> </body> </html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<!DOCTYPE html>
<html>
<head>
    <title>Flappy Bird</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
        // Edit by xingoo
        // Fork on my github:https://github.com/xinghalo/CodeJS/tree/master/HTML5
        var ctx;
        var cwidth = 400;
        var cheight = 600;
        var objects = [];
        var birdIndex = 0;
        var ver1 = 10;
        var ver2;
        var gravity = 2;
        var pipe_height = 200;
        var velocity = 10;
        var tid;
        var score = 0;
        var isScore = false;
        var birds = ["./images/0.gif","./images/1.gif","./images/2.gif"];
        var back = new Background(0,0,400,600,"./images/bg.png");
        var up_pipe = new UpPipe(0,0,100,200,"./images/pipe.png");
        var down_pipe = new DownPipe(0,400,100,200,"./images/pipe.png");
        var ground = new Background(0,550,400,200,"./images/ground.png");
        var bird = new Bird(80,300,40,40,birds);
        objects.push(back);
        objects.push(up_pipe);
        objects.push(down_pipe);
        objects.push(ground);
        objects.push(bird);
        function UpPipe(x,y,width,height,img_src){
            this.px = x;
            this.py = y;
            this.pwidth = width;
            this.pheight = height;
            this.img_src = img_src;
            this.draw = drawUpPipe;
        }
        function DownPipe(x,y,width,height,img_src){
            this.px = x;
            this.py = y;
            this.pwidth = width;
            this.pheight = height;
            this.img_src = img_src;
            this.draw = drawDownPipe;
        }
        function drawUpPipe(){
            var image = new Image();
            image.src = this.img_src;
            ctx.drawImage(image,150,500,150,800,this.px,this.py,this.pwidth,this.pheight);
        }
        function drawDownPipe(){
            var image = new Image();
            image.src = this.img_src;
            ctx.drawImage(image,0,500,150,500,this.px,this.py,this.pwidth,this.pheight);
        }
        function Background(x,y,width,height,img_src){
            this.bgx = x;
            this.bgy = y;
            this.bgwidth = width;
            this.bgheight = height;
            var image = new Image();
            image.src = img_src;
            this.img = image;
            this.draw = drawbg;
        }
        function drawbg(){
            ctx.drawImage(this.img,this.bgx,this.bgy,this.bgwidth,this.bgheight);
        }
        function Bird(x,y,width,height,img_srcs){
            this.bx = x;
            this.by = y;
            this.bwidth = width;
            this.bheight = height;
            this.imgs = img_srcs;
            this.draw = drawbird;
        }
        function drawbird(){
            birdIndex++;
            var image = new Image();
            image.src = this.imgs[birdIndex%3];
            ctx.drawImage(image,this.bx,this.by,this.bwidth,this.bheight);
        }
        function calculator(){
            if(bird.by+bird.bheight>ground.bgy ||
                ((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&(    bird.by<up_pipe.py+up_pipe.pheight))||
                ((bird.bx+bird.bwidth>up_pipe.px)&&(bird.by>up_pipe.py)&&(bird.bx+bird.bwidth<up_pipe.px+up_pipe.pwidth)&&(    bird.by<up_pipe.py+up_pipe.pheight))||
                ((bird.bx>down_pipe.px)&&(bird.by>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by<down_pipe.py+down_pipe.pheight))||
                ((bird.bx>down_pipe.px)&&(bird.by+bird.bheight>down_pipe.py)&&(bird.bx<down_pipe.px+down_pipe.pwidth)&&(bird.by+bird.bheight<down_pipe.py+down_pipe.pheight))){
                clearInterval(tid);
                ctx.fillStyle = "rgb(255,255,255)";
                ctx.font = "30px Accent";
                ctx.fillText("You got "+score+"!",110,100)
                return;
            }
            ver2 = ver1+gravity;
            bird.by += (ver2+ver1)*0.5;
            if(up_pipe.px+up_pipe.pwidth>0){
                up_pipe.px -= velocity;
                down_pipe.px -= velocity;
            }else{
                up_pipe.px = 400;
                down_pipe.px = 400;
                up_pipe.pheight = 100+Math.random()*200;
                down_pipe.py = up_pipe.pheight+pipe_height;
                down_pipe.pheight = 600-down_pipe.py;
                isScore = true;
            }
            if(isScore && bird.bx>up_pipe.px+up_pipe.pwidth){
                score += 1;
                isScore = false;
                if(score>0 && score%10 === 0){
                    velocity++;
                }
            }
            ctx.fillStyle = "rgb(255,255,255)";
            ctx.font = "30px Accent";
            if(score>0){
                score%10!==0?ctx.fillText(score,180,100):ctx.fillText("Great!"+score,120,100);
            }
        }
        function drawall(){
            ctx.clearRect(0,0,cwidth,cheight);
            var i;
            for(i=0;i<objects.length;i++){
                objects[i].draw();
            }
            calculator();
        }
        function keyup(e){
            var e = e||event;
               var currKey = e.keyCode||e.which||e.charCode;
               switch (currKey){
                case 32:
                    bird.by -= 80;
                    break;
            }
        }    
        function init(){
            ctx = document.getElementById('canvas').getContext('2d');
            document.onkeyup = keyup;
            drawall();
            tid = setInterval(drawall,80);
        }
    </script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="400" height="600" style="margin-left:200px;">
    Your browser is not support canvas!
</canvas>
</body>
</html>

接下去是bird的draw属性,那些天性首若是将bird给画出来

总结

在上学玩乐开辟的时候,笔者猛然驰念起高校的情理。当时很纳闷,学计算机学什么物理,后来再接触游戏支付才精晓,未有早晚的情理知识,根本不能模拟游戏中的种种场景。

而透过那一个大约的小游戏,也捡起来了多数旧文化。

  1. Bird.prototype.draw = function () {  
  2.   
  3.                 ctx.drawImage(this.img, 0, 0, this.img.width, this.img.height, this.x, this.y, this.w, this.h);  
  4.   
  5.                 return this;  
  6.             };  

本文由必威发布于必威-前端,转载请注明出处:canvas是一个可以让我们使用脚本绘图的标签betw

TAG标签:
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。