Ashish Soni
Ashish Soni

Reputation: 63

How to wait for all images are loaded from loadfromjson to canvas in fabric js?

I want to hide the loader when all images are loaded on canvas. Currently, what happens it's not waiting for images loaded on canvas. Help is appreciated.

loader.show();
canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
   loader.hide();
});

Upvotes: 2

Views: 2742

Answers (3)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

The method support a callback, that you are using with canvas.renderAll.bind(canvas) Instead of calling that function call your own function to render and hide the loader.

loader.show();
canvas.loadFromJSON(json, function() {
   canvas.renderAll();
   loader.hide();
});

The third function is used only to process each object after initialization and gets called once per object.

Upvotes: 4

Daniel
Daniel

Reputation: 8647

From docs you can read that the third function is called

after each fabric object created.

So it will hide the loader when the first image will be loaded.

You can use counter inside the body of function(o, object) and check if the counter achieved a number of expected images to show, and then hide the loader.

Upvotes: 1

Chong Lip Phang
Chong Lip Phang

Reputation: 9279

You need to use Promise.all(), something like:

function loadImg(json){
   return new Promise((resolve,reject)=>{
      canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
         resolve();
      })
   });
}

Then:

loader.show();
Promise.all(jsonArr.map(loadImg)).then(loader.hide);

I am unable to give you a definite answer due to some ambiguity, but it should be along this line.

Upvotes: 0

Related Questions