将HTML页面转换为图片

25 阅读1分钟

没有将 HTML 网页转换为图像的本机浏览器方式。

但是,有可用的库使用 HTML5 canvas 来模仿这种行为。

试试

html2canvas

html2canvas.hertzen.com/

例如,

<body>
  <h1>Hello World</h1>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos iusto
    vero minus earum enim neque dolore delectus tenetur quaerat voluptatum!
  </p>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
  
  <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</body>

html2canvas(document.querySelector("body")).then((canvas) => {
  var ctx = canvas.getContext("2d");
  var img = new Image();
  img.src = canvas.toDataURL();

  const a = document.createElement("a");
  a.innerText = "Click To Download";
  a.download = true;
  a.href = img.src;
  
  // Clicking on this hyperlink will download an image of document body
  document.body.appendChild(a); 
});