实现页面局部截图保存到本地

需求是点击保存图片将页面的echarts图表和对应表单生成图片保存到本地

使用的包:html2canvas

安装

npm i [email protected]

使用

import html2canvas from 'html2canvas';

generateShareImage() {
​
        const canvas = document.createElement("canvas")
        let canvasBox = document.getElementById('imageWrapper')
        const width = canvasBox.offsetWidth
        const height = canvasBox.offsetHeight
        canvas.width = width * 2
        canvas.height = height * 2
        
        // 生成页面模糊时,可以放大一定倍数,通过调整canvas的宽高使其清晰度增加
        // const context = canvas.getContext("2d");
        // context.scale(1.5, 1.5);
​
        const options = {
          backgroundColor: null,
          canvas: canvas,
          useCORS: true
        };
​
        html2canvas(canvasBox, options).then((canvas) => {
          let dataURL = canvas.toDataURL("image/png");
          //下载
          this.downloadImage(dataURL);
          //显示
          var share = document.getElementById('shareImg');
          share.src = dataURL;
        })
      },
​
      downloadImage(url) {
        let link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "截图.png");
        link.click();
      }

完成

你可能感兴趣的:(实现页面局部截图保存到本地)