我已经在StackOverflow上查看了许多已回答的问题,并且已经实现了我已经找到了我认为正确的代码,但是我无法通过键盘按下来移动我的角色。这有什么问题?
Javascript文件
var key = [];
document.addEventListener('keydown',
function(e){
handleKeyPress(e);
});
onkeydown = onkeyup = function(e){
e = e || event;
map[e.keyCode] = e.type == 'keydown';
if (key[65]){ //'a' is pressed
if (crxpos > 8)
crxpos-=8;
}
else if (key[68]){ //'d' is pressed
if (crxpos < 1280 - 40)
crxpos+=8;
}
else if (key[83]){ //'s' is pressed
if (crypos < 720 - 40)
crypos+=8;
}
else if (key[87]){ //'w' is pressed
if (crypos > 8)
crypos-=8;
}
}
var map = document.getElementById("map");
var ctx = map.getContext("2d");
var dt = 1000 / 30.0;
var caverunner = new Image();
caverunner.src = "caverunner.png";
caverunner.addEventListener("load", drawImage);
var crxpos = 1280 / 2 - 4;
var crypos = 720 / 2 - 4;
function drawImage(){
setInterval(update, dt);
}
function update(){
ctx.clearRect(0, 0, 1280, 720);
ctx.drawImage(caverunner, crxpos, crypos);
}
HTML文件
<!DOCTYPE html>
<html>
<style type="text/css" media="all"> @import "canvas.css"; </style>
<body>
<h1>Cave</h1>
<canvas id="map" width="1280" height="720" style="border:1px solid #000000;"></canvas>
<p> </p>
<script src="cave.js"> </script>
</body>
</html>