HTML canvas game (1)

Source: Internet
Author: User

Today, I tried to simulate an HTML web game, which is very simple. Directly run the Code:

HTML files are simple:

<!DOCTYPE html>

The game. js file is as follows:

// 1. create a canvasvar canvas = document. createelement ("canvas"); // create a canvas var CTX = canvas. getcontext ("2D"); // The contextid parameter specifies the type you want to draw on the canvas. Currently, the unique valid value is "2D", which specifies a 2D drawing, and causes this method to return an environmental object, which exports a 2D drawing API. Canvas. width = 512; // set the canvas height canvas. Height = 480; // set the canvas width. Document. Body. appendchild (canvas); // Add the canvas to the body. // The first thing we need to do is to create a canvas element. In this step, I use JavaScript instead of HTML, because the former is simpler. After the deployment is available, we can reference the text, set the scale, and add it to the document. // 2. add the background image var bgready = false; var bgimage = new image (); bgimage. onload = function () {// when bgimage is loaded, bgready = true ;}; bgimage. src = "images/background.png"; // hero image var heroready = false; var heroimage = new image (); heroimage. onload = function () {heroready = true ;}; heroimage. src = "images/hero.png"; // var monsterready = false; var monsterimage = new image (); monsterimage. onload = function () {monsterready = true; }; Monsterimage. src = "images/monster.png"; // images are required for games of course! So we need to upload an image. I hope to simplify it as much as possible, so I only use one image instead of packaging it with beautiful classes. Bgready is used to tell the canvas when it can be safely painted, Because Dom errors may be thrown if it is arranged before being loaded. // 3. game object var hero = {speed: 256 // speed, moving pixels per second}; var monster ={}; var monsterscaught = 0; // now, we define the variables that will be used later. Hero is installed through speed (that is, moving pixels per second. Monster won't move, so it's a coordinate. Finally, mosterscaught saves the number of monsters captured by players. // 4. player input // handle keyboard input var keysdown ={}; addeventlistener ("keydown", function (e) {keysdown [E. keycode] = true ;}, false); addeventlistener ("keyup", function (e) {Delete keysdown [E. keycode] ;}, false); // it is time to input the operation. It may be the first obstacle for programmers with a background in Web development. The key is to remember that we do not need to immediately respond to input events. In the Web stack, it may be more appropriate to start animation or request data when the user initializes the input. However, in this process, we hope that the logic of this game is to retain greater control. Therefore, you only need to enter and save the user input later. The keysdown variable can save the keycode of any event. If the key code is in the object, you can press this button. That's simple. // 5. new game // when the player catches the devil, restart the game var reset = function () {hero. X = canvas. width/2; hero. y = canvas. height/2; // randomly place the devil monster. X = 32 + (math. random () * (canvas. width-64); monster. y = 32 + (math. random () * (canvas. height-64) ;}; // The reset function is called to start a new game or set a new game level. It places the player's Role in the center of the screen, while the monster positions are randomly placed. // 6. update object var update = function (modifier) {If (38 in keysdown) {// press and hold the keyboard up arrow hero. y-= hero. speed * modifier;} If (40 in keysdown) {// press the keyboard down arrow hero. Y + = hero. speed * modifier;} If (37 in keysdown) {// press and hold the keyboard to the left arrow hero. x-= hero. speed * modifier;} If (39 in keysdown) {// press and hold the keyboard to the right arrow hero. X + = hero. speed * modifier;} // whether the devil if (hero. x <= (monster. X + 32) & amp; monster. x <= (hero. X + 32) & hero. Y <= (monster. Y + 32) & amp; monster. Y <= (hero. Y + 32) {++ monsterscaught; Reset () ;}}; // The UPDATE function can be called each time multiple options are operated. It can check the "Up, down, left, and right" buttons to see if the user has pressed these buttons. If you press it, the player role moves in the corresponding direction. // It may be confusing to send the modifier parameter to update. You can see in the main function that it is referenced, but here we will explain that modifier is an opportunity time amount, and its base is 1. if one second passes, the value will be 1, and the player's role's speed will be multiplied by 1, which means that the player has moved 256 pixels in this second. In the past half a second, the value is 0.5, and the player's moving speed is multiplied by 0.5. And so on. The call speed of this function is so fast that the modifier value is very low, but using this mode ensures that players can move orange at the same speed, regardless of whether the script is running fast or slow. Now we move the role based on the player input. We can check this. If there is a conflict between the player role and the monster, that's right. We can score and reset the game. // 7. object arrangement var render = function () {If (bgready) {CTX. drawimage (bgimage, 0, 0);} If (heroready) {CTX. drawimage (heroimage, hero. x, hero. y);} If (monsterready) {CTX. drawimage (monsterimage, monster. x, monster. y);} // score CTX. fillstyle = "RGB (250,250,250)"; CTX. font = "24 pxhelvetica"; CTX. textalign = "Left"; CTX. textbaseline = "TOP"; CTX. filltext ("Catch the devil number:" + monsterscaught, 32, 32) ;}; // when you see slow movements, the game becomes interesting, so let's draw everything out. First, place the background image on the canvas, and then the player role image and the monster image. Note that the order of placement is very important, because there will be overwrites between images. // Next we will change the font-related text attributes and call filltext to display the player scores. Because we do not have a complex animation or movement method, we only need to complete the above textures. // 8. main game loop var main = function () {var now = date. now (); var Delta = now-then; Update (delta/1000); render (); then = now ;}; // The main game loop controls the game process. First, we need to obtain the current timestamp to calculate the Delta value (How many milliseconds have elapsed since the last interval ). The regulator is sent to update by dividing by 1000 (the number of milliseconds in one second. Call render and record the timestamp. // 9. Start the game reset (); var then = date. Now (); setinterval (main, 1); // This is the last piece of code. First, call reset to start a new game/set a new game level. Then we start the timestamp with the then variable and start interval.

 

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.