<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js" type="text/javascript" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js" type="text/javascript" charset="utf-8"></script>
<div id="app">
  <div class="head">
    <h1>绫绵院-照片添加水印工具</h1>
    <p v-if="tips === 'ok'">水印添加完成,<span @click="download">下载</span></p>
    <p v-text="tips" v-else></p>
    <span class="renovate" @click="reload">刷新</span>
  </div>
  <div class="box" @drop="dropImg " @dragover="dragover">
    <div class="img" :id="'capture'+index" v-for="(item, index) in imageUrl" :key="index">
      <img :src="item">
      <div class="watermark"></div>
    </div>
    <b>拖拽图片到这里(支持多张)</b>
  </div>
</div>
 <script type="text/javascript" charset="utf-8">
   let vue = new Vue({
      el: '#app',
      data: {
        tips: '',
        imageUrl: [],
        fileList: []
      },
      methods: {
        // 阻止默认事件
        dragover(e) {
          e.stopPropagation();
          e.preventDefault();
          e.dataTransfer.dropEffect = 'copy';
        },
        // 拖拽
        dropImg(e) {
          this.tips = '开始添加水印'
          e.stopPropagation();
          e.preventDefault();
          this.fileList.push(...e.dataTransfer.files)
          this.fileList.forEach((item, index) => {
            let reader = new FileReader()
            let imgResult = ''
            reader.readAsDataURL(item)
            reader.onloadend = () => {
              this.imageUrl.push(reader.result)
              if (this.imageUrl.length >= this.fileList.length) {
                this.tips = 'ok'
              } else {
                this.tips = `正在添加水印(${this.imageUrl.length}/${this.fileList.length})`
              }
            }
          })
        },
        // 刷新
        reload() {
          window.location.reload();
        },
        // 点击下载
        download() {
          this.tips = '开始下载,请稍等'
          setTimeout(() => {
            this.fileList.forEach((item, index) => {
              this.downloadImg(item, index)
            })
          }, 10)
        },
        // 下载
        downloadImg(item, index) {
          html2canvas(document.querySelector("#capture" + index), {
             useCORS: true,//Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy
                       allowTaint: false,//Whether to allow cross-origin images to taint the canvas
          }).then(canvas => {
            var url = canvas.toDataURL(item.type);
            var a = document.createElement("a");
            var event = new MouseEvent("click", {
              bubbles: true,
              cancelable: true,
              view: window
            });
            a.download = item.name;
            a.href = url;
            a.dispatchEvent(event);
            if (index === this.fileList.length - 1) {
              this.tips = '下载完成,请刷新页面'
            }
          })
        }
      }
    })
</script>