前端html导出图片

611 阅读1分钟

html2canvas 导出图片(包含滚动条超出部分)

项目中有需求对html进行图片导出,于是找到了html2canvas插件。官方链接:html2canvas官方文档

直接上代码

安装好插件后, 点击按钮调用printOut (name)  // name为所要下载的html标签,用id或class均可以

dataURLToBlob (dataurl) {
      // ie 图片转格式
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1]); let n = bstr.length; const
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },

    downloadResult (name) {
      // 超出内容,滚动条部分处理
      const tableWidth = this.$refs.topology.clientWidth // 具体内容的宽度
      const tableHeight = this.$refs.topology.clientHeight // 具体内容的高度
      const targetDom = document.querySelector(name)
      const copyDom = targetDom.cloneNode(true)
      copyDom.style.width = tableWidth
      copyDom.style.height = tableHeight
      document.querySelector('body').appendChild(copyDom)
      const options = { useCORS: true, backgroundColor: null }

      const canvasID = document.body
      const a = document.createElement('a')
      html2canvas(copyDom, options).then((canvas) => {
        const dom = document.body.appendChild(canvas)
        dom.style.display = 'none'
        a.style.display = 'none'
        document.body.removeChild(dom)
        const blob = this.dataURLToBlob(dom.toDataURL('image/png'))
        a.setAttribute('href', URL.createObjectURL(blob))
        a.setAttribute('download', name + '.png')
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(blob)
        document.body.removeChild(a)
      })
    },

    printOut (name) {
    // 个人观察只是截取可见范围以及以下的区域,所以先将滚动条置顶
      $(window).scrollTop(0) // jQuery 的方法
      document.body.scrollTop = 0 // IE的
      document.documentElement.scrollTop = 0 // 其他
      this.downloadResult(name)
    }
  }

女友睡前故事小程序