html2canvas填坑之路

html2canvas填坑之路
 最后更新于 2024年10月01日 23:00:08

html2canvas的详细介绍可以去 官方文档 查看。实现原理就是将DOM节点绘制到canvas画布上,然后就可以转换成图片实现其它逻辑了。

但是生成的效果与DOM并不是100%相同的

一、兼容性

Loading...

二、问题总结

1、生成的图片里面为什么缺失微信头像或其他图片?

跨域问题导致图片资源获取不到。即便是canvas的画布中对于图片的域也是有要求的。

  • 前后台协同解决方案
  1. html2canvas 的配置项中配置 allowTaint:trueuseCORS:true (二者不可共同使用)
  2. img标签增加 crossOrigin='anonymous'
  3. 图片服务器配置 Access-Control-Allow-Origin 或使用代理。该步骤必须,否则无效
  • 前端单独解决方案

使用代理插件。如: html2canvas-proxy-nodejs 或者是 superagent

下面是 superagent 示例代码:

const request = require('superagent');
const proxHost = 'https://thirdwx.qlogo.cn'; // 指定跨域图片的地址

app.use('/proxy', function (req, res, next) {
  let urlPath = req.url;
  urlPath = decodeURI(urlPath);

  if (!urlPath) {
    return next();
  }

  const reqStream = request.get(`${proxHost}${urlPath}`);
  reqStream.on('error', function (err) {
    console.error('error', err);
  });

  return reqStream.pipe(res);
});

2、生成的图片模糊不清且有锯齿

移动端中 Ration 屏幕造成的图片模糊。改造原生代码,添加两个配置项。查看 新增配置项。新增 scaledpi,推荐使用 scale

// 获取DOM高度
let imgHeight = window.document.querySelector('.content').offsetHeight;
// 获取DOM宽度
let imgWidth = window.document.querySelector('.content').offsetWidth;
// 获取设备像素比
let scale = window.devicePixelRatio;

html2canvas(window.document.querySelector('.content'), {
  useCORS: true,
  scale: scale,
  width: imgWidth,
  height: imgHeight
}).then((canvas) => {
  window.document.querySelector('.content').remove();

  let elemImg = `<img src='${canvas.toDataURL('image/png')}' id='canvas-img' style='height: ${imgHeight}px;border-radius: 10px;width:${imgWidth}px'/>`;

  window.document.querySelector('.container').innerHTML = elemImg;
});

3、生成的图片中若包含二维码,微信长按图片偶现无法识别?

该问题主要出现在使用单页面框架(如VUE)的页面。 使用 window.location.href 直接跳转刷新页面,而不是使用路由切换到二维码页面中。

location.href="www.abc.com/share/xxx"

4、生成的图片中文字间距较大?

这个暂时无法完美解决,可以尝试用CSS属性 letter-spacing 来设置字间距。