html2canvas保存或者上传图片的base64

async exportPic(name, date, upload?) {
    this.isDownLoad = true
    let that = this
    await setTimeout(() => {
      // dailyReport是$refs节点(里面放需要生成图片的html)
      let _canvas = this.dailyReport 
      // let w = parseInt(window.getComputedStyle(_canvas).width)
      // let h = parseInt(window.getComputedStyle(_canvas).height)
      let w = parseInt(_canvas.offsetWidth)
      let h = parseInt(_canvas.scrollHeight) // 滚动内容需要用scrollHeight
      console.log(w, h, '456456')
      let canvas2 = document.createElement('canvas')

      // 放大canvas画布,然后放在较小的容器内,像素会升高
      canvas2.width = w * 2
      canvas2.height = h * 2
      canvas2.style.width = w + 'px'
      canvas2.style.height = h + 'px'

      let context = canvas2.getContext('2d')
      context.scale(2, 2)
      html2canvas(_canvas, {
        canvas: canvas2,
        useCORS: true, // 允许跨域,跨域图片才能在图片中显示
      }).then(async function (canvas) {
        if (upload) {
          console.log('上传图片')
          if (Number(that.type !== 0)) {
            date = that.imageData.recordDateBegin + '_' + that.imageData.recordDateEnd
          }
          let pictureBase64 = canvas.toDataURL('image/jpeg', 2)
          let params = {
            reportType: that.type,
            reportDate: date,
            userId: name.userId,
            reportId: name.reportId,
            pictureBase64,
          }
          const res = await that.$api.report.uploadReport(params)
          if (res.success && res.code === 0) {
            that.$message({
              type: 'success',
              message: '上传图片成功',
            })
            // that.reload()
          } else {
            that.$message({
              type: 'error',
              message: res.msg,
            })
          }
          return that.$emit('fatherMethod')
        }
        let fileName =
          `${name}\xa0${date}` +
          `${that.type === 0 ? '学习日报' : that.type === 1 ? '学习周报' : '学习月报'}` +
          '.jpg'
        // let imgUrl = canvas.toDataURL('image/jpeg', 2) // 获取生成的图片的url
        // 下载方法
        let link = document.createElement('a') // a标签下载
        link.href = canvas.toDataURL('image/jpeg', 2)
        let base64Data = canvas.toDataURL('image/jpeg')
        console.log(base64Data, '图片的数据', upload)
        link.download = fileName
        link.click()
        window.URL.revokeObjectURL(link.href)
        that.isDownLoad = false
      })
    }, 50)
  }
上一篇:vue实现截图并下载


下一篇:记录 html2canvas 生成海报