<!DOCTYPE html>
<html>
<head>
  <title>Div to Image with Width</title>
  <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
  <div id="content" style="width: 300px; border: 1px solid #000;">
    <h1>Hello, Div to Image!</h1>
    <p>This is a simple example.</p>
  </div>

  <button id="convertButton">Convert to Image</button>

  <script>
    const convertButton = document.getElementById('convertButton');
    const contentDiv = document.getElementById('content');

    convertButton.addEventListener('click', async () => {
      const contentWidth = contentDiv.offsetWidth; // Get the width of the content div

      const canvas = await html2canvas(contentDiv, {
        width: contentWidth, // Set the canvas width to match the content div's width
      });

      // Convert canvas to image
      const image = canvas.toDataURL('image/png');

      const a = document.createElement('a');
      a.href = image;
      a.download = 'content.png';
      a.click();
    });
  </script>
</body>
</html>
最后修改:2024 年 04 月 02 日
如果觉得我的文章对你有用,请随意赞赏