在将 Canvas HTML 图像下载为 PNG 之前弹出甜蜜警报提示 [英] Sweet Alert Pop up Prompt Before Downloading Canvas HTML Image to PNG

查看:16
本文介绍了在将 Canvas HTML 图像下载为 PNG 之前弹出甜蜜警报提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Canvas 绘图应用程序中,我有一个下载到 png 按钮,我想制作它,以便只有当用户在我的甜蜜警报弹出提示上单击是的保存它"时,画布上的图像才会下载.现在它仍在自动下载.谢谢您的帮助.(另外,如果有人有更好的方式通过 Javascript 下载也有帮助,它正在下载 png,但它已损坏,我无法打开它)

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>

推荐答案

你应该包含 canvas-toBlob.jsFileSaver.js 进入您的页面,然后:

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

这篇关于在将 Canvas HTML 图像下载为 PNG 之前弹出甜蜜警报提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆