js + html2canvas 实现将div生成图片并保存到本地,自定义图片名。

1. 效果图

在这里插入图片描述 在这里插入图片描述

2. 实现代码

1)导入html2canvas
① 下载完成后,导入dist文件夹下的html2canvas.js

yarn add html2canvas

② 导入后报错
在这里插入图片描述

解决:
打开导入的html2canvas.js
在文件最后一行有 //# sourceMappingURL=html2canvas.js.map 修改为 // /# sourceMappingURL=html2canvas.js.map

2)逻辑实现

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./html2canvas.js"></script>
  <style>
    #box {
      width: 200px;
      height: 200px;
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <div id="box">
    <div style="height:30px;display: flex;">
      <div style="text-align:center;width: 70%;line-height: 30px;">标题部分</div>
      <button id="btn">下载</button>
    </div>
    <div style="background-color: rgb(254, 254, 178);height: 150px;">
      <p>这里是要截图的部分。</p>
      <p>背景颜色是黄色的。</p>
    </div>
  </div>
  <script>
    // 功能:按钮点击事件
    btn.onclick = function (e) {
      // 调用函数获取图片路径
      let picDom = e.target.parentNode.nextElementSibling // 结构不同会有差别
      convertToImage(picDom).then(res => {
        // 将图片下载到本地
        var x = new XMLHttpRequest();
        x.open("GET", res, true);
        x.responseType = 'blob';
        x.onload = function (e) {
          var url = window.URL.createObjectURL(x.response)
          var a = document.createElement('a');
          a.href = url
          a.download = '自定义图片名'
          a.click()
        }
        x.send();
      })
    }
    // 功能:生成快照
    const convertToImage = (container, options = {}) => {
      // 1. 设置放大倍数
      const scale = window.devicePixelRatio;
      // 2. 传入节点原始宽高
      const _width = container.offsetWidth;
      const _height = container.offsetHeight;
      // 3. html2canvas配置项
      const ops = {
        _width,
        _height,
        useCORS: true,
        allowTaint: false,
      };
      return html2canvas(container, ops).then(canvas => {
        // 4. 返回图片的二进制数据
        return canvas.toDataURL("image/png");
      });
    }
  </script>
</body>

</html>

3. 实际应用

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值