Canvas using JS and do a little game html5

This is a very simple game html5, by learning the original Bowen himself to do some renovation,

Now attach the original blog post link

 

 

This is a screenshot of the game:

1. Number of calculated caught monster

2. background, hero, monster.

 

Step one: Create html files and js files

Establish a games folder, create a folder js files, images folders, as well as index.html in the folder.

game.js on js folder, the picture on the images folder.

 

html code is as follows:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Simple Canvas Game</title>
	</head>
	<body>
		<script src="js/game.js"></script>
	</body>
</html>

 

Step two: how to make such a game

We first need to understand the flow of the game is like. This game is very simple, simply grab the monster, the player up and down by manipulating the keyboard to move so as to make the hero caught monsters, and then record the score.

 

We need a game environments and characters to allow players to operate

 

1. First, we create a canvas to canvas as a stage of the game.

Created by the canvas tag element, and then we set the width height of the canvas after canvas so that added to the page.

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

2. Then we add the corresponding pictures (background, heroes, monsters)

Simply create a picture object, and beReady This variable is used to identify whether the image has finished loading.

// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
	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";

// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
	monsterReady = true;
};
monsterImage.src = "images/monster.png";

3. Add the hero, monsters, recorded scores of variables

After the resources are loaded, we construct an object of hero monster, because the game is very simple, so just refresh random monster stationary position, but only one hero attributes like speed, start and score a zero.

// Game objects
var hero = {
	speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;

 

4. Get the user's input

Because the front-end development, the general user clicks triggered the event before going to a movie, or perform asynchronous request and the like, but the logic of the game here want to be more compact while also timely response to input. So we put the user's input to be preserved rather than an immediate response. To do this, use keysDownthis object to save the user presses a key ( keyCode), if you press the keys in this object, then act accordingly.

The default is keyboard input, so we listen keysdown and keysup.

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

 

5. Start a Game

reset method used to start a new round of games, In this method we will be heroes back into the center of the canvas while the monster into a random place.

// Reset the game when the player catches a monster
var reset = function () {
	hero.x = canvas.width / 2;
	hero.y = canvas.height / 2;

	// Throw the monster somewhere on the screen randomly
	monster.x = 32 + (Math.random() * (canvas.width - 64));
	monster.y = 32 + (Math.random() * (canvas.height - 64));
};

 

6. Update Objects

For updating the screen update function that will be called repeatedly laws. First, it checks the user is not currently hold down direction keys and then let the hero to move in that direction hero. The incoming modifier variable is a factor starts at 1 and change over time based. For example, one second later, its value is 1, the rate will be multiplied by a hero, that is 256 pixels per second movement; half a second if it is 0.5, the speed is multiplied by 0.5 hero That hero moves at a speed half the normal speed within this half a second. In theory because this update method is called very fast and frequent, so modifierthe value is very small, but with this factor, no matter how fast we run the code, are able to ensure the movement speed of the hero is constant.

We would also like to increase border checks hero move, otherwise it will go out to the map.

// Update game objects
var update = function (modifier) {
	if (38 in keysDown && hero.y > 32) { // Player holding up
		hero.y -= hero.speed * modifier;
	}
	if (40 in keysDown && hero.y < canvas.height-64) { // Player holding down
		hero.y += hero.speed * modifier;
	}
	if (37 in keysDown&& hero.x > 32) { // Player holding left
		hero.x -= hero.speed * modifier;
	}
	if (39 in keysDown&& hero.x < canvas.width-64) { // Player holding right
		hero.x += hero.speed * modifier;
	}

	// Are they touching?
	if (
		hero.x <= (monster.x + 32)
		&& monster.x <= (hero.x + 32)
		&& hero.y <= (monster.y + 32)
		&& monster.y <= (hero.y + 32)
	) {
		++monstersCaught;
		reset();
	}
};

 

7. rendering objects

First, the background picture out, and then do the same to heroes and monsters drawn, pay attention to the order of the object before the object would otherwise back cover.

After we changed the scoreboard through the relevant attributes of the canvas.

// 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("抓住的怪物: " + monstersCaught, 10, 10);
};

 

8. The main function of loop

The main function of the control flow of the game, first get the current time used to calculate the time difference (over the last is called from the main function of how many milliseconds). Obtained modifierdivided by 1000 (i.e. the number of milliseconds in one second) and then pass the updatefunction. Finally, call render the function and survive this time.

// The main game loop
var main = function () {
	var now = Date.now();
	var delta = now - then;

	update(delta / 1000);
	render();

	then = now;

	// Request to do this again ASAP
	requestAnimationFrame(main);
};

Because use is requestAnimationFrame, so we have to pay attention to the browser compatibility process.

// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

 

9. We can start the game in the browser

First, an initial setting time variable thenfor the first run mainfunction used. And then call the  reset function to start a new game

// Let's play this game!
var then = Date.now();
reset();
main();

 

Guess you like

Origin blog.csdn.net/qq_42488433/article/details/83994736