Web Development

/ 0评 / 3/ 最后更新:2021-12-06
html2canvas截图白屏,图片偏移终极解决方案

需求场景

需要实现活动页面,点击分享弹出海报图片,并长按保存
实现效果

图片偏移原因一:滚动条相关

html2canvas的参数中,有2个参数,x,y。是裁剪位置的x,y坐标。x方向一般没有滚动条,问题不大,y方向一般是有滚动条的,这个时候就要算上滚动条偏移的距离才可以。

图片偏移原因二:transform属性

解决掉滚动条导致的偏移问题后,ios下截图没有偏移问题了,但是安卓会出现。经过多次调试及搜索相关资料,终于发现是因为弹窗使用了transform属性。后来去掉transform使用flex解决了。

截图空白原因三:图片未加载完成就调用html2canvas

这个问题也是显而易见的,图片还没加载好就截图,肯定会出现问题。

其他问题:图片跨域

需要使用useCORS属性,并且服务器开启Access-Control-Allow-Origin : *,当然也可以使用代理方式

终极解决方案代码

const sharePosterImg = ref("");

// 等待海报中的图片加载完成
await loadImage(needLoadImg);
// vue等待页面渲染完成
nextTick(() => {
          const sharePoster = document.getElementById("share-poster");
          //计算图片宽高,偏移距离,滚动条偏移距离
          html2canvas(sharePoster, {
            //允许跨域
            useCORS: true,
            scale: 2,
            width: sharePoster.offsetWidth,
            height: sharePoster.offsetHeight,
            x: sharePoster.getBoundingClientRect().left,
            //需要加上滚动条偏移距离
            y: window.pageYOffset + sharePoster.getBoundingClientRect().top,
          }).then((canvas) => {
            //赋值base64
            sharePosterImg.value = canvas.toDataURL("image/png");
          });
  });
3

Leave a Reply

Your email address will not be published. Required fields are marked *