使用html2canvas形成当前页面的快照(包含滚动条下的内容),支持下载和弹窗预览

170 阅读1分钟

定义一个组件DownloadRef

  • 将某个页面形成快照显示在弹窗中,支持预览和下载
 <div class="download-ref">
    <span
      class="el-icon-camera-solid"
      title="形成快照"
      @click="captureElement"
    />

    <el-dialog
      title="快照预览"
      :visible.sync="dialogVisible"
      append-to-body
      custom-class="el-dialog__download-ref"
    >
      <el-image
        style="width: 100%; height: 100%"
        :src="screenshot"
        :z-index="0"
        :preview-src-list="[screenshot]"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="download">下载</el-button>
      </span>
    </el-dialog>
  </div>
  • 使用DownloadRef组件,父组件传入需要截图的dom
<DownloadRef :current-dom="currentSnapshotDom" />
this.currentSnapshotDom = this.$refs.saveRef
  • 在DownloadRef中接收
props: ['currentDom']
  • 弹窗预览快照的方法
    async captureElement() {
      const dom = this.currentDom
      setTimeout(async() => {
        try {
          const canvas = await html2canvas(this.currentDom, {
            height: dom.scrollHeight,
            width: dom.scrollWeight,
            windowHeight: dom.scrollHeight + dom.clientHeight // 包含滚动条下的内容
          })
          this.screenshot = canvas.toDataURL('image/png') // 这里获取预览的url
          this.dialogVisible = true
        } catch (error) {
          console.error('截图失败:', error)
        }
      }, 100)
    }
  • 下载预览的快照
  download() {
      this.dialogVisible = false
      const x = new window.XMLHttpRequest()
      x.open('GET', this.screenshot, true)
      x.responseType = 'blob'
      x.onload = () => {
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = `${this.getDate()}-首页快照`
        a.click()
      }
      x.send()
    }