html2canvas生成图片下载简易demo

一、完整代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML to Canvas Image</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>

    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
      }
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 400px;
        height: 200px;
        background-color: lightblue;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 20px;
        position: relative;
        overflow: hidden;
      }

      .img {
        width: 100%;
        position: absolute;
        object-fit: cover;
        z-index: 10;
      }

      .title {
        position: absolute;
        z-index: 11;
      }

      #generateButton {
        margin-left: 5%;
      }
    </style>
  </head>
  <body>
    <div class="container" id="container">
      <h1 class="title">Sample Content</h1>
      <img class="img" src="./img/1.jpg" alt="" />
    </div>
    <button id="generateButton">Generate and Download Image</button>
    <script>
      const container = document.getElementById("container");
      const generateButton = document.getElementById("generateButton");
      generateButton.addEventListener("click", () => {
        html2canvas(container).then((canvas) => {
          const image = canvas.toDataURL("image/png");
          // 创建一个下载链接并触发下载
          const a = document.createElement("a");
          a.href = image;
          a.download = "generated_image.png";
          a.click();
        });
      });
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web_icon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值