dom-to-image icon indicating copy to clipboard operation
dom-to-image copied to clipboard

Image is often missing on first render on Safari iOS

Open DanielStout5 opened this issue 4 years ago • 40 comments

I'm using domtoimage.toPng(element) where element contains a few different elements, including a .png img that has partial transparency.

That img is missing from the resulting data URL on the first call on iPhones. Subsequent calls do include the img. There are two other img inside element that always show up in every toPng result, including the first one. Those other .pngs have transparency as well, but it isn't partial - they are either fully opaque text on a fully transparent background.

DanielStout5 avatar Jun 25 '20 13:06 DanielStout5

same problem!

cloydlau avatar Jun 25 '20 14:06 cloydlau

My fix was to stop using domtoimage and use html2canvas instead.

DanielStout5 avatar Jun 27 '20 10:06 DanielStout5

It was working fine with me on chrome, but on iphone usually it miss some pictures. I changed domtoimage.toJpeg(element) to domtoimage.toPng(child) I tested it on multiple mobiles, it seems working fine.

Try it from your side and let me know how it goes with you 👍

domtoimage.toPng(element)
const doc = new jsPDF("p", "mm", "a4");
doc.addImage(page, 'JPEG', 0, 0, 210, 297);

sombek avatar Jul 01 '20 16:07 sombek

It was working fine with me on chrome, but on iphone usually it miss some pictures. I changed domtoimage.toJpeg(element) to domtoimage.toPng(child) I tested it on multiple mobiles, it seems working fine.

Try it from your side and let me know how it goes with you 👍

domtoimage.toPng(element)
const doc = new jsPDF("p", "mm", "a4");
doc.addImage(page, 'JPEG', 0, 0, 210, 297);

Update: It is still there 🙃 I am planning to do something I will update you in couple of hours

sombek avatar Jul 02 '20 06:07 sombek

Heey I think I workaround it -not 100% sure yet- 😂

I tried to run the converter function couple of times then take the last page. I used this function as image generator

function generateImage() {
    return new Promise(resolve => {
        const doc = new jsPDF("p", "mm", "a4");
        const node = this.$refs.content;
        domtoimage.toPng(node)
            .then((page) => {
                doc.addImage(page, 'JPEG', 0, 0, 210, 297);
                return resolve(doc);
            })
    })
}

And use it like this:

generateImage().then(() => {
    console.log("first time")
    generateImage().then(() => {
        console.log("one more time to make sure ")
        generateImage().then((doc) => {
            console.log("okay now it should be fine")
            doc.save(`my_great_file.pdf`)
        })
    })
})

I just pushed this to our production, I hope it works fine with me. *Note: it might take sometime, I add a loader just make it more user friendly

sombek avatar Jul 02 '20 07:07 sombek

I really recommend just using html2canvas - it's more customizable, faster, and reliable. No need to generate the image multiple times, all elements are included in the first one. (I'm unaffiliated with that library)

DanielStout5 avatar Jul 02 '20 08:07 DanielStout5

I really recommend just using html2canvas - it's more customizable, faster, and reliable. No need to generate the image multiple times, all elements are included in the first one. (I'm unaffiliated with that library)

I've just stopped using this because it's very unreliable on how it processes the image, text is weird and it's not supported on safari it seems. Shame.

Heey I think I workaround it -not 100% sure yet- 😂

I tried to run the converter function couple of times then take the last page. I used this function as image generator

function generateImage() {
    return new Promise(resolve => {
        const doc = new jsPDF("p", "mm", "a4");
        const node = this.$refs.content;
        domtoimage.toPng(node)
            .then((page) => {
                doc.addImage(page, 'JPEG', 0, 0, 210, 297);
                return resolve(doc);
            })
    })
}

And use it like this:

generateImage().then(() => {
    console.log("first time")
    generateImage().then(() => {
        console.log("one more time to make sure ")
        generateImage().then((doc) => {
            console.log("okay now it should be fine")
            doc.save(`my_great_file.pdf`)
        })
    })
})

I just pushed this to our production, I hope it works fine with me. *Note: it might take sometime, I add a loader just make it more user friendly

I've just leveraged this package in a similar way by calling it once, then a second time before returning the image to the user. Seems to work this way... however I don't expect this package to be updated any time soon so it'll do for now... 😬

mikerodham avatar Jul 11 '20 16:07 mikerodham

Heey I think I workaround it -not 100% sure yet- 😂

I tried to run the converter function couple of times then take the last page. I used this function as image generator

function generateImage() {
    return new Promise(resolve => {
        const doc = new jsPDF("p", "mm", "a4");
        const node = this.$refs.content;
        domtoimage.toPng(node)
            .then((page) => {
                doc.addImage(page, 'JPEG', 0, 0, 210, 297);
                return resolve(doc);
            })
    })
}

And use it like this:

generateImage().then(() => {
    console.log("first time")
    generateImage().then(() => {
        console.log("one more time to make sure ")
        generateImage().then((doc) => {
            console.log("okay now it should be fine")
            doc.save(`my_great_file.pdf`)
        })
    })
})

I just pushed this to our production, I hope it works fine with me. *Note: it might take sometime, I add a loader just make it more user friendly

Did not work for me... 😞. maybe some one find another solution?

Nevoss avatar Jul 23 '20 09:07 Nevoss

domtoimage(node).then(dataUrl => { domtoimage(node).then(dataUrl1 => { console.log(dataUrl1) }) }) 很蠢,但是可以解决问题

hyl1374961656 avatar Sep 02 '20 08:09 hyl1374961656

Running domtoimage multiple times does not work with ios 13

shameersalim avatar Oct 12 '20 13:10 shameersalim

Still no solutions?

When I build my ionic app it doesn't work the first time, second time works flawlessly. It makes no sense.

There are no errors, I tried with try catch, no error neither... Idk

eddsaura avatar Dec 09 '20 18:12 eddsaura

This is a serious issue and needs to be addressed :( Stuck there....

haris-crewlogix avatar Mar 16 '21 09:03 haris-crewlogix

html2canvas

hyl1374961656 avatar Mar 16 '21 09:03 hyl1374961656

html2canvas

For us it didn't work the same way, like the image was rescaled or something strange. We finally ended up launching 2 times the app at the very first time, hahaha I know...

eddsaura avatar Mar 17 '21 10:03 eddsaura

@eddsaura did you manage to solve the issue? Please share the approach with us as well :)

haris-crewlogix avatar Mar 17 '21 11:03 haris-crewlogix

Same problem! Seems to happen only on Safari on MacOS (not iOS) I'm creating a GIF out of multiple images created by dom-to-image. The first render seems to miss the images included in my DOM, background color of my div is visible in the output.

christian-reichart avatar Mar 18 '21 17:03 christian-reichart

The problem occurs on iOS as well. I ended up using html2canvas.

shameersalim avatar Mar 18 '21 18:03 shameersalim

@hyl1374961656
Thx bro. I don't know why it works, but it works.

LouiMinister avatar Mar 25 '21 01:03 LouiMinister

any solution for this issue? html2canvas not support ssr so i have to search other way using domtoimage

ihoment-chentao avatar Jul 22 '21 01:07 ihoment-chentao

Html2canvas works for me. I have done extensive testing.

On Wed, Jul 21, 2021, 9:47 PM ihoment-chentao @.***> wrote:

any solution for this issue? html2canvas not support ssr so i have to search other way using domtoimage

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/tsayen/dom-to-image/issues/343#issuecomment-884604894, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABOBID2LPZ4QJUV2U4Q4CULTY52B5ANCNFSM4OIMPODA .

shameersalim avatar Jul 22 '21 01:07 shameersalim

any solution for this issue? html2canvas not support ssr so i have to search other way using domtoimage

I ended up making a "disposable" first render with dom-to-image that I don't use basically. The second render then works.

christian-reichart avatar Jul 22 '21 09:07 christian-reichart

domtoimage(node).then(dataUrl => { domtoimage(node).then(dataUrl1 => { console.log(dataUrl1) }) }) 很蠢,但是可以解决问题

Hi, i try your answer,it`s working! But, do you know why it working?

zhoustudent avatar Oct 24 '21 09:10 zhoustudent

Hey Everyone! Just posting that, yes, this is still an issue with Safari (15.1) and, yes, the workaround is to run domtoimage twice. Here's how I'm doing it:

domtoimage.toJpeg(imageCard, {
    width: 1080,
    height: 1080,
    quality: 0.5,
  }).then(dataUrl => {
  domtoimage
    .toJpeg(imageCard, {
      width: 1080,
      height: 1080,
      quality: 0.5,
    })
    .then(dataUrl2 => {
      //Do your all stuff with dataUrl2...
    });
  });

Interestingly, I only had the missing images problem on the dataUrl that I upload to my API. Bafflingly, all images generated for local download are fine (domtoimage only needs to run once.)

This seems to be only a Safari issue.

Based on the suggestions in this thread, II did try html2canvas when I first encountered the missing images issue, but I don't recommend it: it's super-buggy, doesn't seem to like linear gradients, and I could not get a single image rendering with my setup. Maybe it will work for you?

I can live with the above workaround for now 😄.

kittykatattack avatar Nov 22 '21 15:11 kittykatattack

@kittykatattack i had the same problem with iOS but your answer is correct i try this pice of code in my service and it works! Thanks Problem fixed

jefcoserrca avatar Nov 24 '21 21:11 jefcoserrca

Okay so after much testing I was finally able to solve this. Apparently, the images that were coming from the server were not rendering in safari when converting dom to the image. So after many tries, I came up with the solution of converting the image URL to base64 then using that string to render the dom element i want the image of. After that everything was local to that dom element which then solved my problem

 const exportAsImage = (ext) => {
    try {
      var node = document.getElementById(cause.id);
      var options = {
        quality: 1,
      };
      setLoading(true);

      domtoimage.toPng(node, options).then(function (dataUrl) {
        domtoimage.toPng(node, options).then(function (dataUrl) {
          var link = document.createElement("a");
          link.download = "infaque-impact.png";
          link.href = dataUrl;
          link.click();
          setLoading(false);
        });
      });
    } catch (err) {
      console.log(err.message);
    }
  };

const getBase64FromUrl = async (url) => {
  const base64 = await new Promise((resolve, reject) => {
    toDataUrl(url, function (myBase64) {
      resolve(myBase64); // myBase64 is the base64 string
    });
  });
  return base64;
};

export const toDataUrl = (url, callback) => {
  var xhr = new XMLHttpRequest();
  xhr.onload = function () {
    var reader = new FileReader();
    reader.onloadend = function () {
      callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open("GET", url);
  xhr.responseType = "blob";
  xhr.send();
};

sulmanazhar2 avatar Jan 20 '22 10:01 sulmanazhar2

To convert images to base64 doesn't solve,. Still safari doesn't create images on first render.

I need to create canvas there are how many images in element, times. If images from external domain, it works fine. When images from local server, it needs to create many times.

Issue occurs on ipad and ios and macos.

It's serious problem. There must be a solution...

sportakal avatar Sep 10 '22 17:09 sportakal

even double rendering doesnt work now ,someone create a proper fix without double rendering because the time consumption is too long .

shahidshaLumel avatar Sep 12 '22 11:09 shahidshaLumel

Double rendering stopped working at some stage. Tried html2canvas but it doesn't work will with transform, rotate, overflow: 'hidden' and SVG. So all renders are really messy.

Still looking for a solution. Only occurring on Safari and iOS.

MrOli3000 avatar Sep 23 '22 00:09 MrOli3000

Calling domtoimage.toPng twice did fix for me on Safari and iOS.

Livshitz avatar Sep 27 '22 19:09 Livshitz

I recently started using the library and came up with this same error. I think I've found the cause and it is not from the library. Apparently each browser renders images with svg sources differently. In Safari the embedded images inside the svg appear to load very slowly the first time the browser encounters them, and sometimes they never load (unless you append the element visibly to the DOM).

The solution can be:

  • Call the domtoimage.toSvg() directly and append an image with that svg to the DOM
  • You have to wait for all the elements of the svg to load correctly before drawing it to a canvas (This is what the library fails to do on its built in .toPng, .toJpg, etc..).
  • From there you can take that image and draw it on a canvas, then convert it to another format.

The process is a little longer than using the built in functions of the library but results are a lot more consistent.

Code example:

domtoimage.toSvg($element).then(async (svgData) => { // Call the .toSvg function

    let $svgImg = new Image(); // Svg container img
    $svgImg.src = svgData; // Set the svg data as src

    const $canvas = document.createElement('canvas'); // Create a rendering canvas
    $canvas.width = $element.offsetWidth; // Set canvas width same as svg image
    $canvas.height = $element.offsetHeight; // Set canvas height same as svg image
    var ctx = $canvas.getContext("2d");
    
    document.appendChild($svgImg); // Append svg to the DOM for rendering

    $svgImg.onclick = async function () { // Wait for svg to render then click it

        ctx.drawImage($svgImg, 0, 0); // Draw the fully rendered svg to the canvas

        // Use canvas functionality to export its data (in this case to a png file)
        const dataUrl = $canvas.toDataURL(); 

        // Do what you need with the data
        let $pngImg = new Image();
        $pngImg.src = dataUrl;
        document.appendChild($pngImg); 

    };

});

I know this doesn't satisfy every use case, but if you can wait for a PREVIEW svg and then perform the conversion this can help. Another thing to note: Sometimes even the preview SVG doesn't load correctly until you interact with the DOM (scroll, click, etc..).

ESCUDIA avatar Jan 26 '23 09:01 ESCUDIA