在react 中使用html2canvas 使用方法和踩坑

1,730 阅读1分钟

文章说明:公司业务需求,需要前端根据DOM结构去生成图片来进行图片分享

技术调研后用的是html2canvas

  1. 安装
 npm install --save html2canvas
 或者用 yarn
 yarn add html2canvas
  1. 使用
    import html2canvas from 'html2canvas'
    
    let dom =document.querySelector("#capture")
    // 基础使用
    html2canvas(dom).then(canvas => {
        document.body.appendChild(canvas)
    });
    // 生成的图片需要下载的使用配置  通过a 标签下载图片
     html2canvas(dom).then(canvas => {
       const link = document.createElement('a');
       const event= new MouseEvent('click');
       link.download='img.png';
       link.href=canvas.toDateURL();
       link.dispatchEvent(event);
    });
    
    // 如果你要拿来生成的图片有网络图片你需要进行配置 前端配置
      html2canvas(dom,{
      useCORS:true,//【重要】开启跨域配置
      allowTaint: true, // 允许跨域图片
      }).then(canvas => {
          
      });
    // 同时需要在html img 上行设置   crossorigin="anonymous" 这个是关键
        <img crossorigin="anonymous" src="xxx" >
    

3.踩坑集合

(1) 移动端图片模糊问题 - 项目中使用背景图片,结果倒出来的图片是模糊的,移动端 不要使用背景图片 html2canvas 转换后的图片会变模糊, 这是问题解决地址 如果要使用背景图的话,用img去获取图片然后用定位的方式去实现,要不然导出来的图片会模糊

(2) 导出的图片默认会带有白色,要设置透明色的话,需要如下配置

    let dom =document.querySelector("#capture")
     html2canvas(dom,{
          useCORS:true,//【重要】开启跨域配置
          allowTaint: true, // 允许跨域图片
          backgroundColor:null,// 设置为null 就会让背景色为透明色
          }).then(canvas => {
       });