下面是我原来的写法,这个写法原来并没有问题,但后面出现图片不完整+ 白屏+ 偏移(下面附有解决方法)

要截图的区域(截取
          <div ref="imageToFile" id="imageToFile">
            <van-col :span="24" class="topPage" :style="{backgroundImage:'url(' + backImg + ')'}" >    
              <img class="vanimage" :src="img | getImgById">
              <div v-if="titleshow" class="redTitle">{{title}}</div>
            </van-col>
            <div style="clear:both;height:1px;width:100%; overflow:hidden; margin-top:-1px;"></div>
          </div>
事件(截取          
        setTimeout(()=>{
            html2canvas(this.$refs.imageToFile, {
              width: this.$refs.imageToFile.firstChild.offsetWidth,
              height: this.$refs.imageToFile.firstChild.offsetHeight,
              useCORS: true
            }).then((canvas) => {// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
              this.images[0] = canvas.toDataURL('image/png');
            })
          }, 200)    

错误图片:
在这里插入图片描述
——— 原因可能是html2canvas留的坑————
解决方法:在生成图片之前先进行操作

 		  window.scroll(0,0) // 首先先顶部
          const targetDom = document.querySelector("#imageToFile") // 获取要截图的元素
          const copyDom = targetDom.cloneNode(true) // 克隆一个
          copyDom.style.width = targetDom.scrollWidth + 'px'
          copyDom.style.height = targetDom.scrollHeight + 'px'
          document.body.appendChild(copyDom) // 添加

          setTimeout(()=>{
            html2canvas(copyDom, {
              width: targetDom.scrollHeight,
              height: targetDom.scrollHeight,
              useCORS: true
            }).then((canvas) => {
              document.body.removeChild(copyDom) // 用完要删除
              this.images[0] = canvas.toDataURL('image/png');
            })
          }, 200)

但做完之后发现样式变了,这是因为我把class写在大的class里,把class单独移动出来即可。
(class错误在大的class里时,完成图的东西没有样式,比如右边就没有红色背景等全部样式)
完成图:
在这里插入图片描述
参考文章: https://www.jianshu.com/p/7d98ace248fd(这里还提到了其他问题)

Logo

前往低代码交流专区

更多推荐