下面是我原来的写法,这个写法原来并没有问题,但后面出现图片不完整+ 白屏+ 偏移(下面附有解决方法)
要截图的区域(截取
<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里时,完成图的东西没有样式,比如右边就没有红色背景等全部样式)
完成图:

|