我想用箭头做一个简单的移动球,所以我做了:
<canvas id="canvas" width="300" height="300" ></canvas>
<script>
var x=120;
var y=120;
var key,pos=0;
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function()
{
ctx.drawImage(img,x,y);
}
img.src="http://www.infogridpacific.com/blog/i/ball_online.png";
document.onkeydown=function(e)
{
pos=1;
key=window.event?e.keyCode:e.which;
}
document.onkeyup=function(e){pos=0;}
setInterval(function()
{
if(pos==0)return;
if(key==37)x-=2;
if(key==38)y-=2;
if(key==39)x+=2;
if(key==40)y+=2;
canvas.width=canvas.width;
ctx.drawImage(img,x,y);
},5);
</script>
http://jsfiddle.net/mageek/ny3uz/6/
但是如果你先从左到右,球会停一秒钟,然后开始向相反的方向移动。知道如何解决这个问题吗?