使用html2canvas将页面导出为图片并自动下载

21 篇文章 0 订阅
9 篇文章 0 订阅

首先安装 “html2canvas”: “^1.0.0-rc.7”

// 引入html2canvas
import html2canvas from 'html2canvas'  
// id 为导出节点ID  imgName 导出文件名称
  getImg(id,imgName) {
      var getPixelRatio = function (context) { // 获取设备的PixelRatio
        var backingStore = context.backingStorePixelRatio ||
          context.webkitBackingStorePixelRatio ||
          context.mozBackingStorePixelRatio ||
          context.msBackingStorePixelRatio ||
          context.oBackingStorePixelRatio ||
          context.backingStorePixelRatio || 0.5;
        return (window.devicePixelRatio || 0.5) / backingStore;
      };
      //生成的图片名称
      var imgNameStr = `${imgName}.jpg`;
      var shareContent = document.getElementById(id);
      var width = shareContent.offsetWidth;
      var height = shareContent.offsetHeight;
      var canvas = document.createElement("canvas");
      var context = canvas.getContext('2d');
      var scale = getPixelRatio(context); //将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。
      canvas.width = width * scale;
      canvas.height = height * scale;
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      context.scale(scale, scale);
  
      var opts = {
        scale: 1,
        background: '#FFFFFF'
      };
      window['pageYoffset'] = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      html2canvas(shareContent, opts).then((canvas)=> {
        context.imageSmoothingEnabled = false;
        context['webkitImageSmoothingEnabled'] = false;
        context['msImageSmoothingEnabled'] = false;
        context.imageSmoothingEnabled = false;
        var dataUrl = canvas.toDataURL('image/jpeg', 1.0);
        this.dataURIToBlob(imgNameStr, dataUrl, this.callback);
      });
  
    }
    dataURIToBlob(imgName, dataURI, callback) {
      var binStr = atob(dataURI.split(',')[1]),
        len = binStr.length,
        arr = new Uint8Array(len);
  
      for (var i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
      }
  
      callback(imgName, new Blob([arr]));
    }
  
    callback(imgName, blob) {
      let a = document.createElement('a')
      a.setAttribute("href", URL.createObjectURL(blob));
     
      a.setAttribute("download", imgName);
      a.onclick =  function () {
        if (navigator.msSaveBlob) {
          return navigator.msSaveBlob(blob, imgName);
        }
      }
      document.body.appendChild(a)
      a.click();
      a.remove();
    };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值