HTML5 Canvas图像移动闪烁

时间:2014-09-19 09:45:32

标签: javascript jquery html5 canvas

在画布中,有一个图像,它在箭头键的事件上移动。 但它在firefox中闪烁,并且在chrome和ie上工作正常。

我不想要只清除画布部分的解决方案,因为我在画布中也添加了其他东西。

以下是我的代码:

var
velY = 0,
velX = 0,
speed = 2,
friction = 0.90,
keys = [],

canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
playerDirection="img/player/player_back.png";

function update() {

    if (keys[38]) {
        if (velY > -speed) {
            velY--;
            playerDirection="img/player/player_back.png";
        }
    }

    if (keys[40]) {
        if (velY < speed) {
            velY++;
            playerDirection="img/player/player_front.png";
        }
    }
    if (keys[39]) {
        if (velX < speed) {
            velX++;
            playerDirection="img/player/player_right.png";
        }
    }
    if (keys[37]) {
        if (velX > -speed) {
            velX--;
            playerDirection="img/player/player_left.png";
        }
    }

    velY *= friction;
    y += velY;
    velX *= friction;
    x += velX;

    if (x >= canvas.width - player.width) {
        x = canvas.width - player.width;
    } else if (x <= 5) {
        x = 5;
    }

    if (y > canvas.height - player.height) {
        y = canvas.height - player.height;
    } else if (y <= 5) {
        y = 5;
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    playerObj = new Image();
    playerObj.onload = function()
    {
        ctx.drawImage(playerObj, x, y);
    };
    playerObj.src = playerDirection;


}

update();


function handlerKeyDown(e)
{
    keys[e.keyCode] = true;
}

function handlerKeyUp(e) {
    keys[e.keyCode] = false;
}

谢谢你。

1 个答案:

答案 0 :(得分:1)

这就是我对“缓存图像”的意思:

var images = {}; // This will contain the Image objects
// Other definitions...

function update() {

    if (keys[38]) {
        if (!images.back) {
            // The image object hasn't been defined yet.
            images.back = new Image();
            images.back.src = "img/player/player_back.png";
        }
        playerObj = images.back;
    }
    // Other checks on the pressed keys
    // ...

    // Computations on the position...

    if (!playerObj.naturalWidth) {
        // If naturalWidth/Height is 0, then the image hasn't been loaded yet.
        // We update the onload listener to draw in the right position.
        playerObj.onload = function() {
            ctx.drawImage(playerObj, x, y);
        };
    // The image has already been loaded, so we just draw it
    } else ctx.drawImage(playerObj, x, y);
}

(作为对你的代码的警告,似乎你想要处理多个按下的键,但序列中上下左右的最后一个总是“胜过”其他键。这真的是你想要的?)