html2canvas截屏问题总结

600 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第7天,点击查看活动详情

截取的图片多了一块

项目中初始了一个默认模板,模板设置为隐藏状态,z-index:-1, 然后根据后台实际数据渲染出多份数据,运用html2Canvas把模板内容截取成图片,缩放一定大小后加载到canvas中,测试时候发现,canvas中的截图底部多了一部分数据,页面结构和渲染代码如下图所示:

image.png

image.png

image.png

排查后发现是把作为模板渲染的z-index:-1的元素仍截取出了部分

这时候需要使用ignoreElement属性

//要截屏id,因为方法是写在子组件里面的
let node = this.$parent.$refs.chart

console.log('parent', this.$parent, this.$parent.$refs)
//截屏元素的宽高
const width = node.clientWidth
const height = node.clientHeight

//截屏参数
let opts = {
    ignoreElements: (element) => {
        //忽略掉id为template的元素
      if (element.id === 'template') {
        return true
      }
      return false
    },
}
html2canvas(node, opts).then((canvas) => {
    //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
    // const img = canvas.toDataURL('image/png')    
    const img = canvas.toDataURL('image/jpeg')
    resolve({ img, width, height })
})

网络图片截屏

官网上说如果要转换为截图的dom中含有跨域图片,需要设置useCORS: trueallowTaint来实现跨域图片截图,但是我在测试中发现还是不行,最后只能把跨域的图片转换为base64图片,然后再用html2Canvas进行截图。。。,不知道为什么上述设置不起作用。。。。

各位如果知道如何跨域截图,还望能不吝赐教!在此多谢了。

 getLogoScreen() {
    return new Promise((resolve) => {
      let node = this.$refs.logo
      let opts = {
        // width: 50,
        // height: 50,
        useCORS: true, //Whether to attempt to load images from a server using CORS
        allowTaint: false, //是否允许跨源图像污染画布
      }
      html2canvas(node, opts).then((canvas) => {
        const img = canvas.toDataURL('image/png')
        resolve(img)
      })
    })
  },