需要用到的插件包
html2canvas
file-saver
jszip
首先时使用html2canvas将dom转成图片,这里的图片格式为base64/png
const base64List=[];
_this.$nextTick(() => {
const imgNodes=document.getElementsByName("imgNode")
for(let node of imgNodes)
{
html2canvas(node,{
backgroundColor: null//无背景,即透明背景图
}).then(resolve => {
let imgUrl = resolve.toDataURL('image/png');
//去除data:image/png;base64,
base64List.push(imgUrl.substring(22))
})
}
})
在使用jszip将base64/png放入zip压缩包,最后使用file-saver 的 saveAs将压缩包下载
下面逻辑需要延迟执行否则可能图片还未生成 可使用setInterval ,校验dom的lenth 和base64List的lenth是否相等后再执行
let blogTitle="图片"
let zip = new JSZip()
let imgs = zip.folder(blogTitle)
for (let i = 0; i < base64List.length; i++) {
imgs.file('photo' + i + '.png', base64List[i], {base64: true})
}
zip.generateAsync({type: 'blob'}).then(function (content) {
saveAs(content, blogTitle + '.zip')
})
备注:
1,html2canvas是将dom转成图片,即相当于在网页上截图。所以使用时需确认dom已生成,(通常可通过调整z-index等方式来隐藏该dom)
2.把图片的base64编码添加进压缩包前必须先剔除前面的"data:image/png;base64," ,去除后再调用jsZip的file方法添加进压缩包,在添加的时候声明base64:true
比如base64编码:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAeCAYAAABe3VzdAAABw0lEQVRYR+3XsWsUURDH8U86JYgIkZRWkkawVEgfFQsRFNQkBlQQkkIsLEVU0ELERkHFRiSEQCyDaIqQQsHCUiwSEP+AaCFooSEy8A5ecXdk38bLFrdw3c6b7/5m5s3vBjT8GWg4n+0AHMQpTGIUe7CCBcxhvY4IdQEP4AlOdoD4iBl8KoWsA7gfz3Aa3/AIrxPIMdzACAIy1F0tgSwFjLgreJ7gplJZc4ZDeIEjuIvb2KgKWQo4hFc4jnu4hb9tkl9OkKHieXztFWAMw5s0EGNY6pA4SjyPw5jAbK8Ar+Jpav5zWOuQeG9S8Azu42bVMpeUOGKipPF7i/EuV8kuPMR0aomY6J9VVCwB3J0mNlSMKb6O312Shmp3tvAxbY/oA6a+6yuY90e/B3M1SoYkv2YW05790WGKc7Vj7V3Dr/99zcT5F/ESH3Ah7eN2efel+y/cTs8u6gA5ineJ6ATeN23VbcUs5I7nC87ic5XyxrslPdiKy+3WJSxjMwPI7VY3x9OVuRQwDh1Oqy7s/nc8SM7lD3bcsLa++iAeIyxXu2dHLX8LqNF/mqr2fOX36/Rg5WQlAX3AEtXq7uK6OSvFN77E/wBnbHgfH2ihGAAAAABJRU5ErkJggg=="