最近看canvas视频,跟着做了一遍,挺基础的实践。记录一下。
功能介绍
- 键盘移动(PC端)上下左右控制右边那个小人人移动,来和中间的小人人进行重叠,重叠一次即算成功,得分+1。
- 触边后提示over,然后重新定位两个小人人的左边
- 用到了 requestAnimationFrame ,主要是为了让移动轨迹变得圆滑(不再使用定时器)
主要代码 js部分
window.onload=function(){
//获得画布元素
var canvas=document.getElementById("canvas");
//获得2维绘图对象
var ctx=canvas.getContext("2d");
var back = new Image();
back.src = "./image/bg.png";
var heroImg = new Image(); //英雄
heroImg.src = 'image/hero.png';
var monsterImg = new Image(); //怪兽
monsterImg.src = 'image/monster.png';
//英雄 怪兽 坐标位置
var hero = {
x:0,
y:0,
speed:1
};
var monster = {
x:0,
y:0
};
//记录得分,50,,
var n = 0;
//渲染事件
function render(){
ctx.drawImage(back,0,0,canvas.width,canvas.height);
ctx.drawImage(monsterImg,monster.x,monster.y,30,30); //怪兽
ctx.drawImage(heroImg,hero.x,hero.y,30,30); //英雄
ctx.font = "30px '微软雅黑'"; //文字
ctx.fillStyle='#fff';
ctx.fillText('你的得分:'+n,50,50);
}
//监听键盘事件
var keydown = {};
this.addEventListener("keydown",function(e){
console.log(e.keyCode);
keydown[e.keyCode] = true;
// e.keyCode 上38 下40 左37 右39
})
this.addEventListener("keyup",function(e){
delete keydown[e.keyCode];
})
function play(){
if(38 in keydown){ //上
hero.y -= hero.speed;
};
if(40 in keydown){ //下
hero.y += hero.speed;
};
if(37 in keydown){ //左
hero.x -= hero.speed;
};
if(39 in keydown){ //右
hero.x += hero.speed;
};
//如果满足 则重新定义两个任务的坐标
if(hero.x <= (monster.x +2) && hero.y <= (monster.y+2)
&& monster.x <= (hero.x +2)
&& monster.y <= (hero.y+2)){
n++;
hero.x = canvas.width/2; //英雄固定的
hero.y = canvas.height/2;
monster.x = Math.floor(Math.random()*canvas.width)-30; //怪兽随机值
monster.y = Math.floor(Math.random()*canvas.height)-30;
}
};
//游戏结束
var over = false; //未结束
function getOver(){
if(hero.x <= 0 || hero.x >= canvas.width ||
hero.y <= 0 || hero.y >= canvas.height){
over = true;
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.font = "30px '微软雅黑'"; //文字
ctx.fillStyle='red';
ctx.fillText('你的得分:'+n+"游戏结束!",50,50);
alert('over');
// n = 0;
}
}
function init(){
render();
play();
getOver();
if(!over){
requestAnimationFrame(init);
}
}
init();
//动画神器 兼容性调整
requestAnimationFrame = requestAnimationFrame ||
webkitRequestAnimationFrame ||
mozRequestAnimationFrame ||
msRequestAnimationFrame ;
}
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src = "test.js"></script>
<title>Ceshi demo ~</title>
</head>
<body>
<canvas id = "canvas" width ="512" height ="480" style="border: 1px solid #000;">
</canvas>
</body>
</html>
静态资源就不贴了。