vue截圖,上傳,下載,預覽


1.   npm install   html2canvas -D  ;

2. 需要截圖的頁面引入 

import html2canvas from 'html2canvas'
3.需要截圖的容器加 ref;
<div ref="imageTofile" class="dashboard-container home-box">
 

js 里面

 getData() {
      getList().then(res => {
        const data = res.data
        setTimeout(() => {
          this.toImage()  //開始截圖
        }, 1000)
      })
    },
  // 截圖   頁面元素轉圖片  此方法最好設置定時器執行
    toImage() {
      // 第一個參數是需要生成截圖的元素,第二個是自己需要配置的參數,寬高等
      html2canvas(this.$refs.imageTofile, {
        backgroundColor: null,
        useCORS: true // 如果截圖的內容里有圖片,可能會有跨域的情況,加上這個參數,解決文件跨域問題
      }).then((canvas) => {
        const url = canvas.toDataURL('image/png')
        this.htmlUrl = url
        // 把生成的base64位圖片上傳到服務器,生成在線圖片地址
        // this.sendUrl()  //上傳
      })
    },
 
// 圖片上傳服務器
    sendUrl() {
      // 如果圖片需要formData格式,就自己組裝一下,主要看后台需要什么參數
      const formData = new FormData()
      // 調用
      const blob = this.baseToBlob(this.htmlUrl)
      const fileOfBlob = new File([blob], new Date().getTime() + '.png')
      formData.append('file', fileOfBlob)
      upLoad(formData).then(res => {
        this.downUrl = res.data.url
      })
    },
     將base64轉換為blob
    baseToBlob(dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      console.log(mime)
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    // 將blob轉換為file
    blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date()
      theBlob.name = fileName
      return theBlob
    },
//預覽  imgUrl :就是截圖生成的base64
downLoad(imgUrl) {
  
      if (window.navigator.msSaveOrOpenBlob) {
        var bstr = atob(imgUrl.split(',')[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        var blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, '商務看板' + '.' + 'png')
      } else {
        // 這里就按照chrome等新版瀏覽器來處理
        const a = document.createElement('a')
        a.href = imgUrl
        a.setAttribute('download', '商務看板.png')
        a.click()
      }
    },
 
//說明一下  ,base64轉化成BLOB 在轉化成file 上傳會按照文件流上傳。
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM