将HTML页面转为数据流

96 阅读1分钟
import html2canvas from "html2canvas"
import axios from 'axios'
/* 利用html2canvas将HTML页面转为数据流
*  参数:
*  refDom:需要转为图片DOM结构的ref
*  id:需要转为图片DOM结构的ID
*  imageName:生成并下载的图片名称,默认年月日时分秒
*  scale:图片缩放比例,默认不缩放
*  imageType下载图片格式,默认png格式weuh 
*  backgroundColor:图片背景色,默认白色 注:透明色传nul
*/
const HtmlToFile = (refDom, id, imageName = '', scale = 1, imageType = "image/png", backgroundColor = '#fff') => {
   if (imageName === '') {
      let nowDate = new Date()
      imageName = nowDate.getFullYear() + (nowDate.getMonth() + 1) + nowDate.getDate() + nowDate.getHours() + nowDate.getMinutes() + nowDate.getSeconds()
   }
   const canvas = document.createElement("canvas")
   const width = parseInt(window.getComputedStyle(refDom).width)
   const height = parseInt(window.getComputedStyle(refDom).height)
   canvas.width = width * scalescale
   canvas.height = height * scale
   canvas.style.width = width + 'px'
   canvas.style.height = height + 'px'
   const ctx = canvas.getContext("2d");
   ctx.scale(scale, scale);
   const options = {
      backgroundColor,
      canvas,
      useCORS: true
   }

   html2canvas(document.querySelector('#' + id), options).then((canvas) => {
      let dataurl = canvas.toDataURL(imageType)
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
         u8arr[n] = bstr.charCodeAt(n);
      }
      let file = new File([u8arr], imageName + ".png", { type: mime });
      let param = new FormData(); //创建form对象
      param.append('file', file, file.name);
      // 如果只需要html生成的图片数据IO流,到param即可。
      // 上传图片
      axios.post('后端接口url', param,{
          headers: {
              // Authorization: 'Bearer ' + token, 
              'Content-Type': 'multipart/form-data',
          }
      }).then(res => {
            // 
      })
}