在vue项目中用html2canvas遇到因为有滚动条截图不完整问题的解决方法(设置height和windowHeight)


最近有业务需求要将某个页面生成图片然后将图片导出,然后我选择用html2canvas进行图片生成.

首先安装html2canvas

npm install html2canvas --save

然后在需要使用的页面导入html2canvas

import html2canvas from 'html2canvas';

生成图片及导出的代码如下



export default {
  methods: {
     printReport() {
        html2canvas(document.getElementById('dialog'), {
          backgroundColor: 'white',
          useCORS: true, //支持图片跨域
          scale: 1, //设置放大的倍数
        })
          .then((canvas) => {
            // 生成图片导出
            const a = document.createElement('a');
            a.href = canvas.toDataURL('image/png');
            a.download = this.title;
            a.click();
          })
    }
  }
}    

结果因为页面有表格有图片内容比较多,出现了纵向的滚动条,截图出来的效果只能截取到视图窗口显示的部分,超出窗口部分则无法生成.我查了一些资料基本都是建议加上以下代码,在生成图片前让页面滚动到最顶端.

window.pageYoffset = 0;

document.documentElement.scrollTop = 0;

document.body.scrollTop = 0;

但是不知道什么原因,我加上这三行代码依然无法成功.没办法我只能再去翻html2canvas的文档,研究与高度相关的属性,最后在设置了如下两个属性后问题终于得到解决!

 html2canvas(document.getElementById('dialog'), {
          backgroundColor: 'white',
          useCORS: true, //支持图片跨域
          scale: 1, //设置放大的倍数
          height: document.getElementById('dialog').scrollHeight,
          windowHeight: document.getElementById('dialog').scrollHeight
        })