我在使用html2canvas的时候出现一个生成的图片偏移不完整的情况

我在使用的时候遇到一个问题:在页面出现滚动条的时候,生成的图片会出现偏移不完整的情况,网上的方法大致都试过了,但是都没有作用,有哪位知道怎么解决吗?

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的时候,是向下偏移的,设置了之后就向上偏移了。

阅读 4.5k
2 个回答

确实是滚动条问题,生成的时候需要滚动条top为0

这问题我以前碰到过, 发一下之前用的代码

const obj = document.querySelector(".content")
const rect = obj.getBoundingClientRect();

const canvasResult = await html2canvas(obj, {
  allowTaint: true,
  useCORS: true,
  x: rect.left,
  y: window.pageYOffset + rect.top,
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题