Search code examples
javascriptasp.nethtml2canvas

html2canvas(document.body) generates error - "Error loading image"


I am trying to take a screenshot with html2canvas and I am getting the error "Error loading image".

My code is fairly simple -

 function SaveScreenshot() {
            html2canvas(document.body).then(canvas => {

                var image = canvas.toDataURL('image/webp');

                try {
                    localStorage.setItem("img1", image);
                }
                catch (e) {
                    console.log("Storage failed: " + e);
                }

            });
            return false;
        }

You can try it yourself. Go to - https://bengurion.azurewebsites.net/gallerynew Take a snap with the webcam using the camera button (or don't. It doesn't really matter). Go to the menu by pressing on the hamburger button. Go to the gallery button (looks like 4 images with people in them).

This is the button that's calling the function.

Please assist.


Solution

  • I'm not pretty sure why you use 'image/webp' MIME type but it is supported only by chrome. I think you can try something like this. Much common way of doing screen shots.

     function SaveScreenshot() {
                html2canvas(document.body).then(canvas => {
    
                    const base64Image = canvas.toDataURL('image/jpeg', 1);
    
                    try {
                        localStorage.setItem("img1", base64Image);
                    }
                    catch (e) {
                        console.log("Storage failed: " + e);
                    }
    
                });
                return false;
            }