关于前端:实现页面局部截图保存到本地

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

应用的包:html2canvas

装置

npm i html2canvas@1.0.0-rc.4

应用

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();
      }

实现

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理