1

I'm unable to retrieve results from the anonymous function used inside the object "tilemap" given below. I believe the onload function creates some sort of asynchronized callback but I'm not sure how could I fix it.

Thanks in advance...

function generateTileMap(imageLocation, w, h, name = "Tilemap") {
     var image = new Image();
     image.src= imageLocation;

     return (image.onload = function () {
         if (image.naturalWidth % w > 0) {
             return false; //if width is out of scope
        }
         if (image.naturalHeight % h > 0) {
             return false; //if height is out of scope
        }

        var tilemap = {
            conf: {
                 name: name,
                 width: w,
                height: h,
                image: image
            },

            frames: (function () { //Unable to return frames. Async?
                 var frames = [];

                for (var i = 0; i < image.naturalHeight / h; i++) {
                    for (var j = 0; j < image.naturalWidth / w; j++) {
                        frames.push({
                            x: j,
                             y: i
                        });
                    }
                }
                return frames;
            })()
        };
        return tilemap;
    })();
}
Anuj Kumar
  • 81
  • 1
  • 7
  • 1
    I think you need to use the promise and once the image is loaded you need to resolve it and go ahead with next operations – Mahesh G Feb 18 '18 at 10:08
  • 1
    @Batman exactly as I guessed. I'm new to the Async structure of JS. Thanks for pointing it out. Also, thank you for redirecting me too, Jonas. – Arda Ntourali Feb 18 '18 at 10:13

0 Answers0