键盘方向键控制人物上下左右行走
演示地址
MYCode
<html>
<head>
<meta charset=utf-8>
<title>html5人物行走</title>
<script>
var canvas;
var ctx;
//role
var role_x=50;
var role_y=50;
var role_width=32;
var role_height=48;
//每个方向有4个状态
role_direction=0;//value[0,3];
role_status=0;//value[0,3];
//box
var box_x=0;
var box_y=0;
var box_width=400;
var box_height=400;
//
var bound_left=0;
var bound_right=box_x+box_width-role_width;
var bound_top=0;
var bound_bottom=box_y+box_height-role_height;
var unit=10;
function draw_role()
{
ctx.clearRect(box_x,box_y,box_width,box_height);
ctx.lineWidth="5";
ctx.strokeStyle="rgb(0,0,0)";
ctx.beginPath();
ctx.strokeRect(box_x,box_y,box_width,box_height);
/*var img=new Image();
img.src="role.png";
ctx.drawImage(img,role_direction*role_height,role_status*role_width,role_width,role_height);*/
var img=new Image();
img.src="role.png";
img.onload=function()
{
//ctx.drawImage(img,0,0,role_width,role_height);
//alert(role_x+","+role_y);
ctx.drawImage(img,role_status*role_width,role_direction*role_height,role_width,role_height,role_x,role_y,role_width,role_height);
};
}
function move_role(event)
{
//鼠标点击移动
/*var mx;
var my;
if(ev.layerX||ev.layerX==0)
{
mx=ev.layerX;
my=ev.layerY;
}
else if(ev.offsetX||ev.offsetX==0)
{
mx=ev.offsetX;
my=ev.offsetY;
}*/
var keyCode;
if(event==null)
{
keyCode=window.event.keyCode;
window.event.preventDefault();
}
else
{
keyCode=event.keyCode;
event.preventDefault();
}
var cur_direction;
switch(keyCode)
{
case 37://left
cur_direction=1;
role_x=role_x-unit;
if(role_x<bound_left)
role_x=bound_left;
break;
case 38://up
cur_direction=3;
role_y=role_y-unit;
if(role_y<bound_top)
role_y=bound_top;
break;
case 39://right
cur_direction=2;
role_x=role_x+unit;
if(role_x>bound_right)
role_x=bound_right;
break;
case 40://down
cur_direction=0;
role_y=role_y+unit;
if(role_y>bound_bottom)
role_y=bound_bottom;
break;
default:
break;
}
if(role_direction==cur_direction)
{
role_status=(role_status+1)%4;
}
else
{
role_direction=cur_direction;
role_status=0;
}
draw_role();
}
/*function animate(now)
{
draw_role();
requestAnimationFrame(animate);
}*/
function init()
{
canvas=document.getElementById("canvas");
ctx=canvas.getContext('2d');
window.addEventListener('keydown',move_role,false);
ctx.clearRect(box_x,box_y,box_width,box_height);
ctx.save();
ctx.lineWidth="5";
ctx.strokeStyle="rgb(0,0,0)";
ctx.beginPath();
ctx.strokeRect(box_x,box_y,box_width,box_height);
draw_role();
ctx.restore();
//setInterval(draw_role,1000);
//setInterval(function (e){animate();},1000/60);
//requestAnimationFrame(animate);
}
</script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="500" height="500"/>
</body>
</html>
人物行走图片
不足之处
如果连续按住方向键,人物行走的动画将会出现闪烁。这个问题没有解决。