How to make a simple game with HTML5 canvas

Source: Internet
Author: User

In order to make it clear that HTML5 makes the simple process of making a game, we first make a very simple game and take a look at the process.
The game is very simple, nothing more than a hero catches the monster to score, then the game starts again, the monster appears in the random location of the map, the hero initialized in the middle of the map. Click [here] (.. /simple_canvas_game-master/index.html "Simple_canvas_game"), we can play this game directly first

! [Simple_game] (figure/1_simple_game.png)

# # 1. Create a Canvas object # #

It is believed that we all know, of course, the code is created by JS dynamic canvas, you can also directly on the HTML page to create a canvas, and then through the ' document.getElementById () ' To obtain, the two methods are no different, just see you more accustomed to which kind of.

Create canvas canvases and get the canvas context
var canvas = document.createelement ("Canvas");
var ctx = Canvas.getcontext ("2d");
Canvas.width = 512;
Canvas.height = 480;
Document.body.appendChild (canvas);

# # 2. Load Picture # #

The game needs images, so let's load some pictures. I want to be as simple as possible, so I only use the image object to do, of course, can also be loaded into the image of the function of a class or any other form. The Bgready in the code is used to identify whether the picture is fully loaded, and only when the picture is loaded, we can use it, and if it is drawn or rendered before loading is complete, JS will report a DOM error.

We will use three images (backgrounds, heroes, monsters), each of which needs to be dealt with.

Background image Bgimage
var bgready = false;
var bgimage = new Image ();
Bgimage.onload = function () {
Bgready = true;
};
BGIMAGE.SRC = "Images/background.png";

One thing to note here is that the ' Bgimage.src ' is written after ' bgimage.onload ' to solve the IE display bug, so it is recommended that everyone write this.

# # 3. Define the objects to be used by the game # #

Game objects
var hero = {
SPEED:256,//the speed at which heroes move every second, i.e. 256px/s
x:0,
y:0
};
var monster = {
x:0,
y:0
};
var monsterscaught = 0;

Define some variables that will be used later. The speed attribute of the Hero object indicates the hero's movement velocity (pixels/second), the Monster object does not move, so it has only a pair of coordinates, and monsterscaught represents the number of monsters the player catches.

# # 4. Handling player Input # #

Keyboard input Processing
var keysdown = {};
AddEventListener ("KeyDown", function (e) {
Keysdown[e.keycode] = true;
}, False);
AddEventListener ("KeyUp", function (e) {
Delete Keysdown[e.keycode];
}, False);

Which key is pressed by the user, handled by the keyboard event, and the keycode of the pressed key is saved in the empty object Keysdown. If a key is encoded in the variable, it means that the user is currently pressing the key.

# # 5. New Games # #

When the hero catches the monster and starts the game again, the hero's position is in the middle of the canvas and the mob is randomly
var reset = function () {
hero.x = CANVAS.WIDTH/2;
HERO.Y = CANVAS.HEIGHT/2;

Place the location of the monster randomly on the map, not beyond the map.
Monster.x = + (Math.random () * (canvas.width-64));
Monster.y = + (Math.random () * (canvas.height-64));
};

Start a new game by calling the Reset function. This function places the hero (that is, the player character) in the middle of the screen and randomly chooses a location to place the monster.

# # 6. Update Object # #

Update Game objects
var update = function (modifier) {
if (in Keysdown) {//On
HERO.Y-= hero.speed * modifier;
}
if (Keysdown) {//Down
HERO.Y + = hero.speed * modifier;
}
if (PNs in Keysdown) {//Left
hero.x-= hero.speed * modifier;
}
if (in Keysdown) {//Right
hero.x + = hero.speed * modifier;
}

Whether to catch monsters
if (
Hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)
) {
++monsterscaught;
Reset ();
}
};

Update has a modifier parameter, which may seem a bit odd. You'll see it in the main function of the game, which is the main function, but I'll explain it here. The modifier parameter is a time-dependent number that starts at 1. If the interval is exactly 1 seconds, its value will be 1, the hero moves the distance is 256 pixels (Hero's speed is 256 pixels/second), and if the interval is 0.5 seconds, it is 0.5, that is, the hero moves the distance is half its speed, and so on. Typically, the interval for the update function call is very short, so the value of the modifier is small, but in this way it ensures that the hero moves at the same speed regardless of the speed of the code execution.

This is not the same as our previous practice, we often move to the right ' x + = Spped ', moving to the left ' x-= Speed ', the previous practice, the equivalent of a given object movement velocity, no matter what the machine, must ensure that each move distance is ' speed ' The length.

We've implemented moving heroes based on user input, but we can also check them as we move heroes to determine if there are other events happening. For example, if a hero collides with a monster-when a hero collides with a monster, we score the player (monsterscaught plus 1) and reset the game (call the Reset function).

# # 7. Render Object # #

Draw everything
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 = "24px Helvetica";
Ctx.textalign = "Left";
Ctx.textbaseline = "Top";
Ctx.filltext ("Goblins caught:" + Monsterscaught, 32, 32);
};

The update function is equivalent to just changing the value, while the render function is a drawing pattern, and the game becomes more interesting when you can see your action, so let's draw it on the screen. First we draw the background image to canvas, then the hero and the monster. Note that the order is important, because any image that is located on the surface will overwrite the pixels below it.

Think about it, every time if the hero's position changes, then we will all the scene including the background are redrawn once, then you see in the interface is like a hero took a step

Next is the text, which is somewhat different, and we call the Filltext function to show the player's score. Because there is no need for complex animations or to move the text, it is OK to just draw a bit.

# # 8. Game Main Loop # #

Game Main Loop
var main = function () {
var now = Date.now ();
var delta = now-then;

Update (delta/1000);
Render ();

then = Now;

Requestanimationframe (main);
};

var w = window;
Requestanimationframe = W.requestanimationframe | | W.webkitrequestanimationframe | | W.msrequestanimationframe | | W.mozrequestanimationframe;

The main loop of the game is used to control the game flow. First we have to get the current time so that we can calculate the time difference (elapsed since the last cycle). It then computes the value of the modifier and gives it to update (the delta must be divided by 1000 to convert it to milliseconds). Last call to render and update the time of the record.

Game main loop is the most important concept in the game, no matter how the game changes, nothing is to move, disappear. While the move disappears, it is nothing more than a redraw of the canvas, so place the moving or vanishing position in the update function and place the canvas in the render function. And over time, it's just that these two function functions have been executing.

# # 9. Start Game # #

var then = Date.now ();
Reset ();
Main ();

It's almost done, this is the last piece of code. First call reset to start a new game. (Remember, this will put the hero in place and randomly place the monsters). Then save the start time to the variable then and start the game's main loop.

How to make a simple game with HTML5 canvas

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.