2

I have a JSON file that contains the names of the image files to be load.

{ "images": ["1.jpg", "2.jpg", "3.jpg"] }

I use the preload() function to load the content of the JSON file using loadJSON()

The problem is that loadJSON is asynchronous, so the information is not available immediately.

When setup starts I have the JSON content, but I still have to load the images using loadImage() (which is what takes more time) and is also asynchronous.

So my code starts executing before the images are loaded, causing problems.

This functions have a callback when ready, so I though about using the callback to indicate that the image has been loaded by incrementing a counter. When this counter reaches the total number of images to be loaded, then I know that all images are ready.

Something like this

let imgData;
let numImagesLoaded = 0;

function preload() {
  imgData = loadJSON("images.json")
}

function setup() {
  // here I should push images into a vector, but that's not what I'm worried about
  let img;
  for (let filename of imgData.images) {

    // when image is ready increase the counter
    loadImage(filename, img => {
      numImagesLoaded += 1;
    });
  }

  // wait in a loop until all images are loaded
  while (numImagesLoaded < imgData.images.length)
  {}

  // Here the loop has finished, so all images are ready
}

However this looks very hacky.

Is there a way of calling loadJSON() synchronously in preload, so it blocks execution until the JSON data is available (which takes very little time) then I can load the images inside preload() and I know that when I reach setup everything is loaded.

I think that's the logic behind having a preload function, however if you have to preload two things which one is dependent on the other like in my case there must be an easy and standard way of doing so.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Sembei Norimaki
  • 745
  • 1
  • 4
  • 11

1 Answers1

1

You can pass a function as a second argument to loadJSON that will be called when the data loads

function preload() {
  imgData = loadJSON("images.json", imgData => {
    for (let filename of imgData.images) {
    loadImage(filename, tmp => {
      numImagesLoaded += 1;
    });
  }
  })
}
Konrad
  • 21,590
  • 4
  • 28
  • 64