bubkoo / html-to-image

✂️ Generates an image from a DOM node using HTML5 canvas and SVG.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Blank Image in Safari

himanshupatil363 opened this issue · comments

We are basically trying to take screenshots of a div which has images as it's child the output we are getting has blank spaces instead of images this works fine on chrome but safari has this issue

👋 @himanshupatil363

Thanks for opening your first issue here! If you're reporting a 🐞 bug, please make sure you include steps to reproduce it.
To help make it easier for us to investigate your issue, please follow the contributing guidelines.

We get a lot of issues on this repo, so please be patient and we will get back to you as soon as we can.

I also encountered this problem

It seems to be a Safari bug that doesn't load the canvas immediately when the web page is rendered.
I tried to fork the code and fix it by setting a timeout when loading an image in util.ts within the createImage function.
from
img.onload = () => resolve(img)
to

 img.onload = () => {
      setTimeout(function () {
        resolve(img);
      }, 300);
    };
commented

img.onload = () => {
setTimeout(function () {
resolve(img);
}, 300);
};

this works in mac safari but doesnt work in ios safari tho after 2-3 times the img does show

img.onload = () => {
setTimeout(function () {
resolve(img);
}, 300);
};

this works in mac safari but doesnt work in ios safari tho after 2-3 times the img does show

Another way you can try is to loop the toCanvas function, but it's not the best practice because you don't know how many times to show the image.

export async function convertHtmlToCanvas(
  targetElement: HTMLElement,
  countReRender: number = 0,
): Promise<HTMLCanvasElement> {
  let canvas: any;
    for (let i = 0; i < countReRender; i++) {
      canvas = await toCanvas(targetElement);
    }
  return canvas;
}

In the same situation, the problems encountered in Safari are a headache,

¿Has anyone found a better solution than the loop solution?

Here's how I fixed mine in Safari. I added delay using modern-screenshot: https://github.com/qq15725/modern-screenshot/tree/main

Which also came from html-to-image.

``
if (!isSafari) {
dataURL = await htmlToImage.toPng(imageElement);
} else {
//put a timer on the domToCanvas for 500ms to make sure the image is loaded
dataURL = await domToCanvas(imageElement, {
delay: 500,
debug: true,
}).then((canvas) => {
dataURL = canvas.toDataURL("image/png");
return dataURL;
});
}