1

我正在尝试创建一个简单的游戏,并在按下左右按钮时,一张图片应该移动(并且在另一张图片和 之间变化trexftrexb

<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 上试试

为什么这不能按我的预期工作?

4

2 回答 2

0

调低您的间隔计时器延迟计数:

http://jsfiddle.net/bTvBn/42/

它现在工作正常。

于 2012-05-29T15:45:48.430 回答
0

这在 Chrome 中对我有用,但是您的绘制间隔太大(1 秒),因此在重绘之前触发了按键事件。

于 2012-05-29T15:41:26.347 回答