下载前 Sweet Alert 弹出提示 Canvas HTML 图片转 PNG

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

在我的 Canvas 绘图应用程序中,我有一个下载到 png 的按钮,我想制作它,以便 canvas 的图像仅在用户单击我的 "yes save it" 时下载甜蜜警报弹出提示。现在它仍在自动下载。谢谢您的帮助。 (如果有人有更好的方法通过 Javascript 下载也会有帮助,它正在下载 png 但它已损坏,我无法打开它)

$('#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>

您应该将 canvas-toBlob.js and FileSaver.js 添加到您的页面中,然后:

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; 
};