canvas绘制以及控制游戏中移动的小人的行为

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
.main {
background-image: url(./img/back.jpg);
width:600px;
height: 370px;
background-size: 600px;
position:relative;
}
</style>
</head>
<body>
<div class="main">
<canvas id="myCanvas" width = "600" height="370" >
您的浏览器不支持canvas。
</canvas>
 
</div>

<div class="group">
<button type="button" class="play">开始</button>
<button type="button" class="stop">暂停</button>
</div>
<!--<img id=‘img‘ src="img/person.png"/>-->

<script>
 
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

function PersonRun() {
this.flag = true;
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;

// -5 到 5
this.dx = Math.round(Math.random() * 10) - 5; // 0 -10之间的像素
this.dy = Math.round(Math.random() * 10) - 5;


//drawImage(img,x,y,w,h) 绘制图片
//var img = document.getElementById("img");
// ctx.drawImage(img,200,100,20,20)
//创建图片 new Image()
var image = new Image();
image.src = ‘img/person.png‘;
//图片加载完后绘制
image.onload = () => {
ctx.drawImage(image, this.x, this.y, 20, 20);
};
this.image = image;

}



//更新位置
PersonRun.prototype.update = function (direction) {

// this.x +=this.dx;
// this.y +=this.dy;
// console.log(this.x);
// console.log(this.y);

switch (direction) {
case ‘left‘:
this.x -= 2;
break;
case ‘right‘:
this.x += 2;
break;
case ‘up‘:
this.y -= 2;
break;
case ‘down‘:
this.y += 2;
break;
default:
this.x += this.dx;
this.y += this.dy;
break;
}
}
//重新绘制
PersonRun.prototype.man = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);//清空画布

ctx.drawImage(this.image, this.x, this.y, 20, 20);

}

var p1 = new PersonRun();
// p1.man();

// 自己跑
// var timer = setInterval(function(){
// p1.update();
// p1.man();
// },500);

//事件监听
document.querySelector(‘.group‘).addEventListener(‘click‘, function (ev) {
var target = ev.target;
switch (target.className) {
case ‘play‘:
if (this.flag) return;
this.flag = true;
timer = setInterval(function () {
p1.update();
p1.man();
}, 500);
break;
case ‘stop‘:
this.flag = false;
clearInterval(timer);
break;
}
});

// onkeydown:键盘按下后触发的事件
// onkeyup:按键抬起后触发的事件
// keyCode 属性返回 onkeydown 或 onkeyup 事件的键的代码。

document.onkeyup = grabEvent;

function grabEvent(ev) {
var keycode = ev.which || ev.keyCode;
switch (keycode) {
case 37://left功能;
clearInterval(timer);
p1.update(‘left‘);
console.log(‘left‘);
break;
case 38://up
console.log(‘up‘);
p1.update(‘up‘);
break;
case 39://right
console.log(‘right‘);
p1.update(‘right‘);
break;
case 40://down
console.log(‘down‘);
p1.update(‘down‘);
break;
}
p1.man();
}

</script>

</body>
</html>

canvas绘制以及控制游戏中移动的小人的行为

上一篇:MYSQL触发器


下一篇:如何更换苹果Mac登录画面的背景桌布?