我正在尝试创建一个简单的游戏,并在按下左右按钮时,一张图片应该移动(并且在另一张图片和 之间变化trexf
)trexb
。
<canvas id="canvas" width="640" height="480" >
Browser doesn't support canvas.
</canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width, height, rightKey = false, leftKey = false, upKey = false, downKey = false, rex_x, rex_y = 300, trexf, trexb;
trexf = new Image('Trexf.png');
trexb = new Image('Trexb.png');
function clearCanvas() {
canvas.width = canvas.width;
}
function drawRex() {
if(rightKey) {
rex_x += 5;
} else if(leftKey) {
rex_x -= 5;
}
ctx.drawImage(trexf, rex_x, rex_y);
if(rightKey == false || leftKey == false) {
ctx.drawImage(trexb, rex_x, rex_y);
}
}
function loop() {
clearCanvas();
drawRex();
}
function keyDown(e) {
if(e.keyCode == 39)
rightKey = true;
else if(e.keyCode == 37)
leftKey = true;
}
function keyUp(e) {
if(e.keyCode == 39)
rightKey = false;
else if(e.keyCode == 37)
leftKey = false;
}
function init() {
ctx.canvas.width = window.innerWidth - 30;
ctx.canvas.height = window.innerHeight - 30;
document.addEventListener('keydown', keyDown, false);
document.addEventListener('keyup', keyUp, false);
rex_x = canvas.width / 2;
setInterval(loop, 1000);
}
init();
在 JSFiddle 上试试。
为什么这不能按我的预期工作?