html2canvas将页面dom元素内容渲染成图片保存至本地

本文展示了如何使用html2canvas库将HTML内容转换为canvas,然后保存为图片。在处理包含服务器图片时,需要设置跨域参数useCORS为true。点击按钮可以下载由HTML内容生成的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html2canvas:https://html2canvas.hertzen.com/configuration/
github:https://github.com/niklasvh/html2canvas

效果
在这里插入图片描述

在这里插入图片描述

代码

<!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="./js/html2canvas.js"></script>
</head>

<body>
  <div id="root">
    <h3>名片</h3>
    <div class="person">
      <img src="./assets/header.png" alt="">
    </div>
  </div>
  <button id="downloadImg">点击</button>
</body>

<script>

  let dom = document.getElementById("downloadImg");
  dom.onclick = function () {
    // 实现保存为图片的第一步:html转为canvas
    html2canvas(document.getElementById("root"), {
      scale: window.devicePixelRatio,
      height: 800,
      width: 800,
      backgroundColor: null//设置背景透明
    }).then(function (canvas) {
      let link = document.createElement('a');
      // 实现保存图片的目标只需要将canvas转image即可。
      // canvas的toDataURL方法将canvas输出为data: URI类型的图片地址,再将该图片地址赋值给元素的src属性即可。
      link.href = canvas.toDataURL();
      // 保存图片
      link.setAttribute('download', '图片canvas.png');
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.removeChild(link)

    });
  }
</script>

</html>

当图片来源于服务器,需要设置跨域

<body>
  <div id="root">
    <h3>名片</h3>
    <div class="person">
      <img style="width: 600px; height: 400px;" src="https://img0.baidu.com/it/u=3976250177,3245140550&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675" alt="">
    </div>
  </div>
  <button id="downloadImg">点击</button>
</body>

<script>

  let dom = document.getElementById("downloadImg");
  dom.onclick = function () {
    // 实现保存为图片的第一步:html转为canvas
    html2canvas(document.getElementById("root"), {
      useCORS: true,//图片设置跨域
      scale: window.devicePixelRatio,
      height: 800,
      width: 800,
      // backgroundColor: null
    }).then(function (canvas) {
      let link = document.createElement('a');
      // 实现保存图片的目标只需要将canvas转image即可。
      // canvas的toDataURL方法将canvas输出为data: URI类型的图片地址,再将该图片地址赋值给元素的src属性即可。
      link.href = canvas.toDataURL();
      // 保存图片
      link.setAttribute('download', '图片canvas.png');
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.removeChild(link)

    });
  }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值