使用html2canvas截取屏幕图片时图片显示不全

Vue微信H5项目中 此页面需要把页面绘制成功一张图片保存
使用了html2canvas完成此功能

在mouted中加载了插件
`~~~~

var opts = {
    useCORS: true, // 允许加载跨域的图片
    allowTaint: false,
    tainttest: true, // 检测每张图片都已经加载完成
    logging: true,
    backgroundColor: null
  }
  html2canvas(document.querySelector('.card'), opts).then(canvas => {
    const imgUrl = canvas.toDataURL('image/png')

    this.dataURL = imgUrl
    this.firstFlag = false})~~~~
  })~~~~`
  

结果出现生成的图片出现空白
不确定图片跨域了(本地开发环境)还是图片没加载完成就生成了图片
尝试了三种解决方案
1.mounted 设置延时器 (电脑可以,真机无效)
2.opts中配置允许跨域 (无效)
3.给img标签设置crossorigin="anonymous"

这三种都不能用
有做过的可以帮忙解答一下吗

阅读 13.8k
3 个回答

对于超过屏幕高度的内容html2canvas无法截取,目前知道的比较好的有两个方法
1、通过复制DOM节点,插入到body下可解决,不过会出现当多个图片层叠的时候元素会出现混乱闪过的情况,不是很好用
2、通过canvas画布解决(推荐)

// 此方法可在图片load完成之后调用
drawToPic () {
    // box -- 需要截取的屏幕的可视区域
    const clientHeight = this.$refs.box.clientHeight
    const width = this.$refs.box.clientWidth
    const cs = document.createElement('canvas')
    cs.width = width * scale
    cs.height = clientHeight * scale
    const content = cs.getContext('2d')
    content.scale(scale, scale)
    const rect = this.$refs.box.getBoundingClientRect()
    content.translate(-rect.left, -rect.top)
    const that = this
    this.$nextTick(() => {
      html2canvas(this.$refs.box, {
        allowTaint: true,
        taintTest: true,
        useCORS: true,
        scale: scale / 2,
        canvas: cs,
        width: width,
        height: clientHeight
      }).then((canvas) => {
          const url = canvas.toDataURL()
          // 微信浏览器下,可长按图片保存
          if (browserType() === 1) {
            this.imgUrl = url
          } else {
            this.imgUrl = URL.createObjectURL(that.base64ToBlob(canvas.toDataURL()))
          }
      })
    }
}
// base64转blob
base64ToBlob (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})
}

浏览器有滚动条么,推荐使用这个截图插件dom-to-image

浏览器有滚动条会出现这种情况,我前不久刚做遇到这个问题。也没找到什么好的方法。我的你可以参考一下。
就是在点击生成海报的按钮时,让页面回到顶部:
// ios
document.documentElement.scrollTop = 0;
// 安卓
document.body.scrollTop = 0;

推荐问题