Question

I'm building a game in Html and Javascript using the <canvas> element. As I need to flip an image horizontally, in adition to the principal canvas I create a secondary one that isn't visible for flipping the images (to avoid downloading another image for the other position) Then I draw the result of the secondary canvas in the principal one. This method works without any problem in Firefox 27, while in Chrome, Chrome mobile, Opera mobile and Firefox mobile for an unknown reason it doesn't.

The code for the secondary canvas is the following:

var flip = function (image) {
'use strict';
var offscreenCanvas = document.createElement('canvas'),
    offscreenCtx = offscreenCanvas.getContext('2d');

offscreenCanvas.width = image.width;

offscreenCtx.translate(image.width, 0);
offscreenCtx.scale(-1, 1);
offscreenCtx.drawImage(image, 0, 0);
return offscreenCanvas;
};

And the code for drawing the result in the principal canvas:

var flippedCharImg = flip(charImg);
ctx.drawImage(flippedCharImg, character.xpos, character.ypos, character.stopped.width, character.stopped.height);

Any idea of why it doesn't work on those browsers and how to make it work?

Sorry for the syntax!

Was it helpful?

Solution

As @Philipp suggests, your code works when I make sure the images are fully loaded before trying to drawImage them.

Here's an image loader that fully loads all image and then calls your code in the start() function:

// first load all your images

var imageURLs=[];  
var imagesOK=0;
var imgs=[];

// put the URLs to any images you need in the imageURLs[] array
imageURLs.push("yourCharImg.png");

loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

// after all images are loaded, start using the images here

function start(){

    // the imgs[] array holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]

    // get an image from the imgs[] array

    var charImg=imgs[0];  // or whatever image index you need

    // draw a flipped image

    var flippedCharImg = flip(charImg);
    ctx.drawImage(flippedCharImg, 
        character.xpos, character.ypos, 
        character.stopped.width, character.stopped.height
    );

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top