Skip to content Skip to sidebar Skip to footer

HTML5 Canvas Image Moving Flickering

In canvas, there is a image, which moves on events of arrow keys. But it flickers in firefox and works fine on chrome and ie. I don't want a solution like to clear only the portion

Solution 1:

This is what I meant with "caching the images":

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);
}

(As an warning on your code, it seems that you want to handle multiple pressed keys, but the last one in the sequence up-down-right-left always "wins" over the others. Is that really what you want?)


Post a Comment for "HTML5 Canvas Image Moving Flickering"