如何使用 html5 和 javascript 使用键盘键移动对象。在这里,我用下面的代码尝试了它,但它没有移动任何人都可以帮助使用键盘箭头键移动对象吗?
<!DOCTYPE html>
<html>
<head>
</head>
<body onLoad="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='green'>
<canvas id="mycanvas"></canvas>
<script>
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0.25 * Math.PI, 1.25 * Math.PI, false);
ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fill();
ctx.beginPath();
ctx.arc(100, 100, 50, 0.75 * Math.PI, 1.75 * Math.PI, false);
ctx.fill();
ctx.beginPath();
ctx.arc(100, 75, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fill();
//moves//
var xpos=500;
var ypos=550;
var xspeed=1;
var yspeed=0;
var maxspeed=5;
//boundaries//
var minx=500;
var miny=200;
var maxx=990;
var maxy=400;
//controller
var upPressed=0;
var downPressed=1;
var leftPressed=0;
var rightPressed=0;
function slowDownX()
{
if(xspeed > 0) xspeed=xspeed-1; if(xspeed<0) xspeed=xspeed+1;
}
function slowDownY()
{
if(yspeed > 0)
yspeed = yspeed-1;
if(yspeed < 0)
yspeed = yspeed+1;
}
function gameLoop()
{
xpos=Math.min(Math.max(xpos+xspeed,minx),maxx); ypos=Math.min(Math.max(ypos+yspeed,miny),maxy);
xpos = document.getElementById('mycanvas').style.left;
ypos = document.getElementById('mycanvas').style.top;
if (upPressed == 1)
yspeed = Math.max(yspeed - 3,-3*maxSpeed);
if (downPressed == 1)
yspeed = Math.min(yspeed + 3,3*maxSpeed)
if (rightPressed == 1)
xspeed = Math.min(xspeed + 1,1*maxSpeed);
if (leftPressed == 1)
xspeed = Math.max(xspeed - 1,-1*maxSpeed);
if (upPressed == 0 && downPressed == 0)
slowDownY();
if (leftPressed == 0 && rightPressed == 0)
slowDownX();
return setTimeout("gameLoop()",10);
}
function keyDown(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 1;
if (code == 40)
downPressed = 1;
if (code == 37)
leftPressed = 1;
if (code == 39)
rightPressed = 1;
}
function keyUp(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 0;
if (code == 40)
downPressed = 0;
if (code == 37)
leftPressed = 0;
if (code == 39)
rightPressed = 0;
}
</script>
</body>
</html>