我在使用的时候遇到一个问题:在页面出现滚动条的时候,生成的图片会出现偏移不完整的情况,网上的方法大致都试过了,但是都没有作用,有哪位知道怎么解决吗?
import HTML2Canvas from 'html2canvas'
function getWinClientHeight() {
let clientHeight = 0
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
} else {
clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
}
return clientHeight
}
function getDocClientHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
export default async function (el, beforeCallBack, afterCallBack) {
if (typeof el === 'undefined') {
console.error('必须传入一个元素')
return false
}
if (typeof beforeCallBack !== 'undefined') {
beforeCallBack()
}
const scale = 1.5
const scrollY = window.scrollY
const scrollX = getDocClientHeight() > getWinClientHeight() ? -8.3 : 0
const canvas = await HTML2Canvas(el, {
width: el.clientWidth,
height: el.clientHeight,
backgroundColor: null,
scale,
scrollX,
scrollY: -scrollY,
useCORS: true
})
if (typeof afterCallBack !== 'undefined') {
afterCallBack(canvas)
return false
}
const resolveUrl = canvas.toDataURL('image/png', 1.0)
return resolveUrl
}
原本没有设置scrollX和scrollY的时候,是向下偏移的,设置了之后就向上偏移了。
确实是滚动条问题,生成的时候需要滚动条top为0