Download html2canvas image to desktop

后端 未结 2 1333
小鲜肉
小鲜肉 2021-01-01 05:41

I found this https://jsfiddle.net/8ypxW/3/ and I would like to know how to download image to desktop. I only see save png but no download if it\'s possible can you give me t

2条回答
  •  醉梦人生
    2021-01-01 05:58

    update 2018

    Notice that in the new versions of Html2Canvas the onrendered option is deprecated and replaced with promises.

    To be able to download the image to the user computer, you may use something like this:


    Html

    
        
        
            

    My content here


    Javascript (plain JavaScript)

    Based on Krzysztof answer

    document.getElementById("download").addEventListener("click", function() {
    
        html2canvas(document.querySelector('#boundary')).then(function(canvas) {
    
            console.log(canvas);
            saveAs(canvas.toDataURL(), 'file-name.png');
        });
    });
    
    
    function saveAs(uri, filename) {
    
        var link = document.createElement('a');
    
        if (typeof link.download === 'string') {
    
            link.href = uri;
            link.download = filename;
    
            //Firefox requires the link to be in the body
            document.body.appendChild(link);
    
            //simulate click
            link.click();
    
            //remove the link when done
            document.body.removeChild(link);
    
        } else {
    
            window.open(uri);
    
        }
    }
    

    Issue encountered

    Indeed i was able to download the image, but it was blank ...the possible cause for this (at least in my case) was that the content wrapper (id="#boundary") has no width or height defined, so specifying a height and a width to the content wrapper did the trick for me.

提交回复
热议问题