将html元素保存为图片

初始需求是echarts绘制的图表保存为图片,

后来发现,echarts图标之外,还有一个参数input/button也要放到图片中

于是,技术实现从简单的《echarts导出为图片》

变成了较为复杂的《html元素导出为图片》

 

先放出已经实现的《echarts导出为图片》的代码,

    // 导出 图片
    generatePic() {
      let parseTime = dayUtils.parseTime(new Date(), '');
      var myChart = document.getElementById('fitModel_echart_Option_Div_all')
      // var myChart = echarts.init(document.getElementById(this.showFitModel_pingjia_factor));
      var img = new Image();
      // pieMyChart1 要导出的图表
      img.src = myChart.getDataURL({
        type: "png",
        pixelRatio: 1, //放大2倍
        backgroundColor: "#000",
      });
      let projectName = this.projectInfo.projectName || ''
      projectName = '敏感性分析:' + projectName
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        var a = document.createElement("a");
        var event = new MouseEvent("click");
        a.download = projectName + "分析结果_图片" + parseTime + ".png" || "下载图片名称";
        // 将生成的URL设置为a.href属性
        a.href = dataURL;
        // 触发a的单击事件
        a.dispatchEvent(event);
        a.remove();
      };
    },
View Code

 

 

照抄的《html元素导出为图片》相关js代码

//获取canvas配置项
    getCanvasOption(shareContent){
      let canvasEle = document.querySelector('canvas');
      if(canvasEle){
        document.getElementById('dialog').removeChild(canvasEle)
      }
      let width = shareContent.offsetWidth; //获取dom 宽度
      let height = shareContent.offsetHeight; //获取dom 高度
      let canvas = document.createElement("canvas"); //创建一个canvas节点
      let scale = 2; //定义任意放大倍数 支持小数

      canvas.getContext("2d").scale(scale, scale); //获取context,设置scale 
      canvas.width = width * scale; //定义canvas 宽度 * 缩放
      canvas.height = height * scale; //定义canvas高度 *缩放

      canvas.style.cssText = 'width: '+ width +'px; height: '+ height +'px';
      let opts = {
          scale: scale, // 添加的scale 参数
          canvas: canvas, //自定义 canvas
          // logging: true, //日志开关,便于查看html2canvas的内部执行流程
          width: width, //dom 原始宽度
          height: height,
          useCORS: true // 【重要】开启跨域配置
      };
      return opts;
    },

     downloadFile(content, fileName) { //下载base64图片
      let base64ToBlob = function(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for(let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
          type: contentType
        });
      };
      let aLink = document.createElement('a');
      let blob = base64ToBlob(content); //new Blob([content]);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },

    //下载图片
    downLoadPic() {     
      let shareContent = document.getElementById('cert');//需要截图的包裹的(原生的)DOM 对象
      let opts = this.getCanvasOption(shareContent);
      this.html2canvas(shareContent,opts).then((canvas) =>{
        // document.getElementById('dialog').appendChild(canvas);
        let context = canvas.getContext('2d');
        // 【重要】关闭抗锯齿
        context.mozImageSmoothingEnabled = false;
        context.webkitImageSmoothingEnabled = false;
        context.msImageSmoothingEnabled = false;
        context.imageSmoothingEnabled = false;
        let MIME_TYPE = "image/png";
        let imgURL = canvas.toDataURL(MIME_TYPE);
        this.downloadFile(imgURL,'文件名')
      });
    },

    //下载pdf
    downLoadPdf() {
      let shareContent = document.getElementById('cert');//需要截图的包裹的(原生的)DOM 对象
      let opts = this.getCanvasOption(shareContent);
      this.html2canvas(shareContent,opts).then((canvas) =>{
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / 592.28 * 841.89
        let leftHeight = contentHeight
        let position = 0
        let imgWidth = 595.28
        let imgHeight = 592.28 / contentWidth * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let PDF = new this.JsPDF('', 'pt', 'a4')
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save('文件名' + '.pdf')
      });
    },

 

posted @ 2024-10-14 11:33  MoreJewels  阅读(13)  评论(0编辑  收藏  举报