Bootstrap

二维码名片批量增加logo处理并下载压缩包

效果图:
在这里插入图片描述
需安装三个插件:
‘html2canvas’
‘jszip’
‘file-saver’

vue 页面主要代码:

<template>
  <div>
      <div><button type="button"  style="width:120px;height:60px;background:#3388cc;color:#fff;margin-bottom:30px;cursor:pointer;" @click="save()">下载所有图片</button>
 </div>
 <a href="" v-for="(item,index) in serviceImg" :id="'link'+index"></a>
    <div class="course-container" v-for="(item,index) in serviceImg"  :id="'myImage'+index"> 
      <div class="course">
          <img :src="require('./assets/png/'+item)"/>
      </div>
      <div class="code">
          <img src="./assets/logo/logo.png"/>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
  export default {
    data() {
      return {
        serviceImg:[],
      }
    },
    created() {
        
    },
    destroyed() {
     
    },
    mounted() {
  	//参数:1.路径;2.是否遍历子目录;3.正则表达式
   let arr  = require.context("./assets/png", true, /\.png$/).keys();
    this.serviceImg=arr.map(item =>(item.replace('./','')));
    console.log(this.serviceImg);
  },

    methods: {
      save() {
        let blogTitle = '二维码名片打包';
        let zip = new JSZip();
        let imgs = zip.folder(blogTitle);
        for(let i = 0;i< this.serviceImg.length;i++){
          html2canvas(document.querySelector("#myImage"+i)).then(canvas => {
          let base64 = canvas.toDataURL("image/png");
          imgs.file(this.serviceImg[i],base64.substring(22), {base64: true});
          if( i == this.serviceImg.length-1){
          console.log(imgs)
          zip.generateAsync({type: 'blob'}).then(function (content) {
            // see FileSaver.js
            FileSaver.saveAs(content, blogTitle + '.zip');
          });
        }
        });
        }
       
      },
     
    }
  }
</script>

<style scoped>
.course-container {
  height: 345px;
  width: 345px;
  position:relative;
  display:inline-block;
  margin-right:20px;
}
 .course {
     z-index: 1;
     position: absolute;
     height: 345px;
     width: 345px;
 }
 .code {
    z-index: 2;
    position: absolute;
    left:130px;
    top:125px;
    width: 80px;
    height: 80px;
   
 }
 .code img, .course img{
      width:100%;
      height:100%;
    }
</style>
;