H5 game development Catch the little dinosaur

Source: Internet
Author: User

The first time I wrote a technical blog, I used to write some life thoughts and record some things that happened in my life.

Bo Master Three students A, currently learning JS for more than a year, is still in the learning stage, what said Bad hope Daniel Pointing, because the first time to write blog, typesetting what needs to be improved, I hope you understand.

This is my study H5 canvas since the first game, the first contact with H5 game, is to see a big Brother code farm Terminator Blog (http://www.cnblogs.com/chaogex/) (basic requirements a little high, and so must be studied thoroughly), Just the lab teacher is ready to call me to write H5 game, read a lot of Canvas API and great God Vajoy (http://www.cnblogs.com/vajoy/) written canvas tutorial, After the foundation of the canvas to see the HTML5 Study Group, the second technical lecture "hand-made HTML5 game" video, under the source code to learn a long time, that period of time has been repeatedly written this game, slowly understand the concept of a lot of games, and then there is a kind of fully confident feeling (don't tease , I do not know anything), of course, this sense of accomplishment is very important, the source of motivation. This is my game development to now nearly 2 weeks of learning experience, share to everyone, hope to be useful to everyone.

        

The game is made out of this effect, played black and white piano people should know, this and the game is similar.

One. Image rendering

People who have written the game know that most games are carried out in the same way as background and Sprite, where rendering pictures are often used, I myself encapsulated a method of image rendering, I hope you give some advice.

  

/** * Author YH * @param imgcount image array must have ID and SRC * @param callback callback function * @returns each Sprite's canvas and context*/functiongetimg (imgcount,callback) {varTotal =imgcount.length, Load= 0, IMG={}, W= 0, H= 0;  for(vari = 0;i < total;i++){        varID =imgcount[i].id; varIMGs =NewImage (); IMGS.SRC=imgcount[i].src; //set the width and height of the canvas        if(Imgcount[i].width &&imgcount[i].height) {W=Imgcount[i].width; H=Imgcount[i].height; }Else{W=Imgs.width; H=Imgs.height; } img["CVS" +id] = document.createelement ("Canvas"); img["CVS" +id].width =W; img["CVS" +id].height =h; img["ct" +id] = img["CVS" +id].getcontext ("2d"); img["CT" +id].drawimage (imgs,0,0,imgs.width,imgs.height,0,0, w,h); //Recycle picture Resources        DeleteIMGs; IMGs=undefined; Imgs.onload=function() {load++;    };        }; if(typeofcallback = = "function"){        varme = This; functionCheck () {if(Load >=Total ) Callback.call (me,arguments); ElsesetTimeout (check,300);    } check ();    }; returnimg;}

Because of the performance problem, every time a picture is loaded, a canvas is created to draw the picture, and of course we don't need to display the canvas. Only for the next time you can use the Getimagedata and Putimagedata method to directly take the data in the canvas to get the picture, not every time to paint, and so on will show you the process of drawing, this method of invocation is this:


var global = getimg ([ {id:"bg", src: "img/bg.png", width:400,height:600}, {id:"di", SRC: "img/1.png", width:100,height:100}, {id:"Hand", src: "img/hand.png", width:100,height:100}, {ID:"PBG", src: "img/game box. png", width:100,height:100}],callback);

Define a variable to access the Getimg return object, here is the method of drawing:

/* * * Based on the ID to get the canvas and context in global, get and put Imageda * target put all canvas objects, the above global
*/ function Draw (Target,context,x,y,id) { var canvas = target["CVS" + ID], = target["ct" + ID], = Ct.getimagedata (0,0, canvas.width,canvas.height); Context.putimagedata (data,x,y);}

This method is not encapsulated very well, because most of the time we need the Sprite animation, is to change the image of the x and Y at any time, this package is only used in this game method, because the game has no sprite animation.

Two. Game class

When the picture is finished, we need to define a game class, write code here, in order to improve performance, using the prototype method, so that each time the JS file loading only one copy, do not waste resources.

Because I do not have GitHub (and have not used such high-end things), can only be posted here code.

functionGame (option) {//Object Extension     for(varattrinchoption) This[attr] =option[attr];} Game.prototype={canvas:NULL, CT:NULL,
High and wide width for default canvas:999, Height:999,
Initialize position x:0, y:0, N:4, M:6,
Define frame fps:30, sleep:0,
Define the position of the array to hold each palm arr:[], click:0, Init:function(){ This. Canvas = document.createelement ("Canvas"); This. Canvas.width = This. Width; This. Canvas.height = This. Height; Document.body.appendChild ( This. Canvas); This. ct = This. Canvas.getcontext ("2d"); This. Sleep = (1000/this. FPS) | This. Time =Date.now (); This. moused =false; }, Update:function(){ This. Initdraw (); This. Move (); },
Initialize Initdraw:function(){ This. DRAWIMG (Global, This. ct,0,0, "BG"); vary = 10; for(vari = 0;i< This. m;i++){ varx = 15; varRan = ((Math.random ()) |); for(varj = 0;j< This. n;j++){ This. DRAWIMG (Global, This. Ct,x,y, "PBG"); if(j = = Ran && i! = This. m-1){
Each time you draw a palm, store his position in an array. This. DRAWIMG (Global, This. Ct,x+5,y+3, "Hand"); This. Arr.push (j); }Else if(j = = ran && i = = This. m-1) This. DRAWIMG (Global, This. Ct,x+5,y+3, "Di"); X+ = 95; } y+ = 98; } This. Listener ( This. arr); }, Drawimg:function(target,context,x,y,id) {varCanvas = target["CVS" +ID]; varCTX = target["ct" +ID]; vardata = Ctx.getimagedata (0,0, Canvas.width,canvas.height); Context.putimagedata (Data,x,y); }, };

The above code to complete the initialization, we first to implement each effect to animate later, we will set the mouse events, as well as the main loop, this is a very important thing, generally a game has only one main loop.

Listener:function(arr) { This. arr =arr; //Get Boundary        varme = This, Index= This. Arr.pop ();  This. y = 402 + 50;  This. x = 15+index*95 + 50; //Add mouse events to determine range         This. Canvas.onmouseup =function(event) {varCX = Event.clientx-me.canvas.offsetleft-me.x, Cy= Event.clienty-me.canvas.offsettop-me.y; if( -50<=cx&& CX <= && -50<= Cy && cy<= 50) {me.moused=true;    }        }; }, move:function(){        varme = This;  This. Mainloop = SetInterval (function() {me.loop (); }, This. Sleep); }, Loop:function(){        varTime = document.getElementById ("Time"); time= (Date.now ()- This. time)/1000; time.innerhtml =Time ; if( This. moused) {             This. moused =false;  This. click++;  This. Reload (); }        if(Time >= 5){             This. DRAWIMG (Global, This. ct,0,0, "over");            Clearinterval (); Alert ("You have gone altogether" + This. click+ "Step"); }}, Reload:function(){        vardata = This. Ct.getimagedata (0,0, This. width, This. Height);  This. Ct.clearrect (0,0, This. width, This. Height);  This. ReDraw ();  This. Ct.putimagedata (data,0,98); }, ReDraw:function(){         This. DRAWIMG (Global, This. ct,0,0, "BG"); vary = 10;  This. J = 0; varx = 15; varRan = ((Math.random ()) |);  for(varj = 0;j< This. n;j++){             This. DRAWIMG (Global, This. Ct,x,y, "PBG"); if(J = =ran) {                 This. DRAWIMG (Global, This. Ct,x+5,y+3, "Hand");  This. Arr.unshift (j); } x+ = 95; }                 This. Listener ( This. arr); }

After each click we will get a copy of the current context Getimagedata, then set to Putimagedata (data,0,100), then re-render the first line once, and then update the values in the array so that it can look like an animation. Compare the level of limited, Daniel look at play, if the level and I can learn, and later we can become Daniel, will also share more and better things.

Recently still studying Masaki's "JS frame design", this book gives me the first feeling is high thought height, the first time I looked at depressed, read the first chapter nothing to understand, and then I did not understand the new concept of Baidu once again, after 2 days finally finished the first chapter, slowly more and more like the book , wrote a self-framework of the seed module, planning to wait for their own framework to find a job later, it should be more relaxed.

H5 game development Catch the little dinosaur

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.