需求:点击【批量下载】按钮,将多张canvas图片下载为压缩包。
1.需要用到jszip
,在项目中安装:npm install jszip
2.实现下载
const download = () => {
let imgs = [bg1, bg2, bg3];
let canvasList: any[] = [];
let request = imgs.map(e => getBase64Image(e));
// 在渲染图片时,img.onload方法是同步的,如果图片过大,会导致图片一张一张被刷出来,影响视觉效果
// 所以将图片的绘制封装为Promise函数,使用Promise.all来获取绘制结果,当全部图片都绘制成功后,再开始下载图片
Promise.all(request)
.then(res => {
canvasList = res;
getZip();
})
.catch(err => {
console.log(err);
});
function getBase64Image(path: any) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = path;
img.onload = function () {
resolve(imgTobase64(img));
};
if (!path) {
reject("image error");
}
});
}
function imgTobase64(img: any) {
const canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 300;
let ctx = canvas.getContext("2d")!;
ctx.drawImage(img, 0, 0, 300, 300);
return canvas.toDataURL();
}
function getZip() {
//创建JSZip实例对象
let zip = new JSZip();
// 创建文件夹
let imgFolder = zip.folder("example")!;
for (let i = 0; i < canvasList.length; i++) {
// 将base64格式转为文件,加入文件夹
imgFolder.file(`${i + 1}.png`, base64ImgtoFile(canvasList[i]), { base64: true });
}
// 生成zip文件并下载
zip
.generateAsync({
type: "blob", // 压缩类型
compression: "DEFLATE", // STORE:默认不压缩 DEFLATE:需要压缩
compressionOptions: {
level: 9, // 压缩等级1~9 1压缩速度最快,9最优压缩方式
},
})
.then(function (content) {
// 下载的文件名
let filename = "download.zip";
// 创建隐藏的可下载链接
let eleLink = document.createElement("a");
eleLink.download = filename;
eleLink.style.display = "none";
// 下载内容转变成blob地址
eleLink.href = URL.createObjectURL(content);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
});
function base64ImgtoFile(dataurl: any, filename = "file") {
let arr = dataurl.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let suffix = mime.split("/")[1];
// atob : 解码使用 base-64 编码的字符串
let bstr = window.atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime,
});
}
}
};