Sweet Alert Pop up Prompt Before Downloading Canvas HTML Image to PNG

天大地大妈咪最大 提交于 2019-12-31 05:16:25

问题


in my Canvas drawing app I have a download to png button, I want to make it so the image off the canvas only downloads when the user clicks "yes save it" on my sweet alert pop up prompt. Right now it's still downloading automatically. Thank you for your help. (also if someone had a better way to download via Javascript that would help too, it's downloading the png but it is corrupt and I can't open it)

$('#download').click(function(){
    swal({
        title: "Are you finished your creation?",  
        text: "click yes to save",   
        type: "warning",  
        showCancelButton: true,   
        confirmButtonColor: "#f8c1D9",   
        confirmButtonText: "Yes, save it!",  
        closeOnConfirm: true 
    }, function (isConfirm) {      
        if (isConfirm) {
            swal("Saving!");

            var base64 = document.getElementById("canvas")
              .toDataURL("image/png")
              .replace(/^data:image\/[^;]/, 'data:application/octet-stream');

            document.getElementById("download-png").href = base64
        } else {

        }

        return false; 
    });
});

html

<div id="download">
    <a href="#" id="download-png" download="image.png"><img src="./assets/imgs/tools/save.png" /></a>
</div>

回答1:


You should include canvas-toBlob.js and FileSaver.js into your page and then:

function (isConfirm) {      
    if (isConfirm) {
        swal("Saving!");

        var canvas = document.getElementById("canvas")

        // get the canvas as a blob
        canvas.toBlob(function(blob){
            // Save the file...
            saveAs(blob, 'my-image.png')
        }, "image/png", 0.95); // PNG at 95% quality
    } else {
        // user cancel
    }

    return false; 
};


来源:https://stackoverflow.com/questions/37709557/sweet-alert-pop-up-prompt-before-downloading-canvas-html-image-to-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!