5

I have a function loadTileSet(). This function must return arrTiles (image data array), but function is returning UNDEFINED. I'm using push to put data into array..

function loadTileSet(){
        var canvas = document.getElementById('fakeCanvas');
        $('#fakeCanvas').hide();
        var ctx = $("canvas")[0].getContext('2d');
        var imgTileSet = new Image();
        imgTileSet.src = 'tileset.png';
        var imageTileNumWidth = 23;
        var imageTileNumHeight = 21;

        var arrTiles = [];

        imgTileSet.onload = function(){

            var imageWidth = imgTileSet.width;
            var imageHeight = imgTileSet.height;
            sndCanvasWidth = imageWidth/imageTileNumWidth;
            sndCanvasHeight = imageHeight/imageTileNumHeight;
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            ctx.drawImage(imgTileSet,0,0,imageWidth,imageHeight);

            var i=0;
            var j=0;
            var t=0;
            for(i=0;i<imageWidth;i+=sndCanvasWidth){
                for(j=0;j<imageHeight;j+=sndCanvasHeight){
                    var myImageData = ctx.getImageData(j,i,sndCanvasWidth,sndCanvasHeight); 
                    arrTiles.push(myImageData);  
                }
            }
            return arrTiles;
        }
    }

and here I try to put array into another

var arrNew = loadTileSet();
console.log(arrNew[0]);
Juliano Lima
  • 709
  • 3
  • 10
  • 17
  • 2
    You are `return`ing from the onload handler, not from the `loadTileSet` function. – Bergi Aug 24 '13 at 14:37
  • 2
    The problem is that the load is done asynchronously, you *cannot* return the imageDate from the function. See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) for possible solutions. – Bergi Aug 24 '13 at 14:38

2 Answers2

6

Bergi's comment already states the problem. This is an async process, so you need to handle it as one. The general idea is to use a callback:

function loadTileSet(callback) {
    // ...

    imgTileSet.onload = function () {
        // instead of return, do this
        callback(arrTiles);
    };
}

loadTileSet(function (arrNew) {
    // now you can use arrNew
});
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
0

your function doesn't return anything. Also, where you are populating the array, it is encapsulated in that .onload function.

CrayonViolent
  • 32,111
  • 5
  • 56
  • 79