Chrome 和 IE 下导出下载图片

2019-11-13  本文已影响0人  一沭丶

基于 canvas 生成的图片,然后下载
兼容性: IE11、IE10、chrome,其他未测

function dataURLToBlob(dataurl) {
    var arr = dataurl.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}


var blob = dataURLToBlob(canvas.toDataURL('image/png', 1));

var url = window.URL.createObjectURL(blob);
var filename = that.canvasConfig.title + ".png";

// IE 11
if (window.navigator.msSaveBlob !== undefined) {
    window.navigator.msSaveBlob(blob, filename);
    return;
}

var a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = filename;
document.body.appendChild(a);

requestAnimationFrame(function () {
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
});
上一篇下一篇

猜你喜欢

热点阅读