html2canvas使用及踩坑记录

1,596 阅读1分钟

本文知乎地址-知不道者

html2canvas 的参数

如何使用

html2canvas(document.querySelector("#capture")).then(canvas => {
    console.log(canvas);
});

大家是否在使用的过程中遇到了白图、跨域、ios不触发then、iframe多次触发等问题,是不是很烦

白图问题

原因:由于页面的滚动,元素fixed

解决:设置参数y值为目标元素顶部距窗口的距离+滚动距离

html2canvaas(ele,{
  y: ele.getBoundingClientRect().top + window.scrollY
})

如果是里面有资源图缺失,那么就是资源未加载完,需要监测资源图加载完毕之后执行

跨域

html2canvaas(ele,{
  useCORS: true,
  y: ele.getBoundingClientRect().top + window.scrollY
})

但是,如果你遇到有的图片还是跨域的话,那么需要使用canvas去把跨域的图片转成base64

const getBase64Image = (src: string) =>
  new Promise((resolve, reject) => {
    const img = document.createElement('img');
    img.crossOrigin = '';
    img.src = src;
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ratio = window.devicePixelRatio || 2;
      const width = img.width * ratio;
      const height = img.height * ratio;
      canvas.width = width;
      canvas.height = height;
      const ctx: any = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);
      try {
        resolve(canvas.toDataURL('image/jpeg', 0.9)); // 这里是为了降低图片大小
      } catch (error) {
        reject(error);
      }
    };
  });

ios不触发then

使用1.0.0-rc.4版本,就酱紫

iframe多次触发

这是由于它遍历了所有的标签对其进行操作了,这其中包括了iframe,不知道会不会有其他src资源也这样,具体什么操作得看看源码,但是怎么解决呢,这个插件还是挺贴心的

html2canvaas(ele,{
  useCORS: true,
  y: ele.getBoundingClientRect().top + window.scrollY,
  ignoreElements: (element: any) => {
     if (element.tagName.toLowerCase() === 'iframe') {
              return element;
        }
       return false;
   },
})

以上是使用html2canvas时遇到的坑,欢迎大家留言自己遇到的问题,一起讨论一下


本文知乎地址-知不道者