How to convert fabric js canvas to image with background Synchronously?

First, I get image url (blob or data64) from another canvas for fabric js canvas’s background. I checked setBackgroundImage works well.

But when I try to save fabric js’s canvas to image, background image are gone. It’s Not exists. I suspect this is because setBackgroundImage function is Asynchronous.

How can I fix it? I want to make it synchronous…

  saveResultImg(src) {
    //set fabric js canvas's background
    canvas.setBackgroundImage(
      src,
      canvas.renderAll.bind(canvas)
    );

    //save fabric js canvas with it's background to image
    const resultImg = new Image();
    resultImg.src = canvas.toDataURL('image/png');
    return resultImg;
  }

Answer

The setBackgroundImage method includes a callback. By moving your toDataURL call inside of the setBackgroundImage callback and then adding a callback to your function, you’ll be able to use that callback to do something with the image once it’s ready.

Change the function to this:

  function saveResultImg(src, callback) {
    //set fabric js canvas's background
    canvas.setBackgroundImage(src, function() {
      canvas.renderAll.bind(canvas)
      //save fabric js canvas with it's background to image
      const resultImg = new Image();
      resultImg.src = canvas.toDataURL('image/png');
      callback(resultImg);
    });
  }

Then call it like this:

saveResultImg(src, function(img) {
  //image is ready
  console.log(img);
});