使用html2Canvas截取页面长图

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>html2canvas 长截图示例</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
      body {
        font-family: Arial, sans-serif;
      }
      #capture {
        width: 100%;
        height: 1500px; /* 模拟长页面 */
        background: linear-gradient(to bottom, #ff9a9e, #fad0c4);
        padding: 20px;
        text-align: center;
      }
      button {
        margin: 20px;
        padding: 10px 20px;
        font-size: 16px;
      }
    </style>
  </head>
  <body>
    <button onclick="captureScreen()">截取长截图</button>
    <div id="capture">
      <h1>html2canvas 长截图测试</h1>
      <p>此页面高度较大,可用于测试滚动截图</p>
      <div
        style="
          margin-bottom: 0;
          width: 100%;
          height: 1000px;
          display: flex;
          flex-direction: column-reverse;
        "
      >
        底部
      </div>
    </div>

    <script>
      function captureScreen() {
        const element = document.getElementById("capture");

        html2canvas(element, {
          useCORS: true, // 处理跨域问题
          scrollX: 0,
          scrollY: 0,
          windowWidth: document.documentElement.scrollWidth, // 获取整个页面宽度
          windowHeight: document.documentElement.scrollHeight, // 获取整个页面高度
        }).then((canvas) => {
          // 转换为图片
          let image = canvas.toDataURL("image/png");

          // 创建下载链接
          let link = document.createElement("a");
          link.href = image;
          link.download = "screenshot.png";
          link.click();
        });
      }
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值