var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 300;
document.body.appendChild(canvas);
ctx.beginPath();
//背景图
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function() {
bgReady = true;
}
bgImage.src = 'https://grewer.github.io/JsDemo/game/images/back.jpg';
//其他图
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function() {
heroReady = true;
}
heroImage.src = 'https://grewer.github.io/JsDemo/game/images/hero.jpg';
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function() {
monsterReady = true;
}
monsterImage.src = 'https://grewer.github.io/JsDemo/game/images/monster.jpg';
//位置,速度,次数
var hero = {
speed: 256,
x: 0,
y: 0
}
var monster = {
x: 0,
y: 0,
vx: (Math.random() * 10 - 5) | 0,
vy: (Math.random() * 10 - 5) | 0
}
var monstersCaught = 0;
//用户输入
var keysDown = {};
addEventListener('keydown', function(e) {
keysDown[e.keyCode] = true;
},
false)
addEventListener('keyup', function(e) {
delete keysDown[e.keyCode];
},
false)
//re
var reset = function() {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
}
var check = function() {
if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {++monstersCaught;
reset();
}
if (monster.y <= 0 || monster.y >= 268) {
monster.vy = -monster.vy
}
if (monster.x <= 0 || monster.x >= 468) {
monster.vx = -monster.vx
}
}
//update
var update = function(modifier) {
if (38 in keysDown) {
hero.y -= hero.speed * modifier;
if (hero.y < 0) {
hero.y = 0;
}
}
if (40 in keysDown) {
hero.y += hero.speed * modifier;
if (hero.y >= 272) {
hero.y = 272;
}
}
if (37 in keysDown) {
hero.x -= hero.speed * modifier;
if (hero.x < 0) {
hero.x = 0;
}
}
if (39 in keysDown) {
hero.x += hero.speed * modifier;
if (hero.x > 472) {
hero.x = 472;
}
}
monster.y += monster.vy;
monster.x += monster.vx;
check();
}
//render
//
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);
}
ctx.fillStyle = 'rgb(0,0,0)';
ctx.font = '24px Helvetica';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText('Monsterrs caught:' + monstersCaught, 32, 32)
}
var main = function() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
requestAnimationFrame(main);
}
var then = Date.now();
reset();
main();
console