Sweet Alert Pop up Prompt Before Downloading Canva

2020-05-03 12: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; 
};