Render HTML document thumbnail

2019-07-21 00:00发布

问题:

Is it possible to get an image of html document using javascript. I am looking for a javascript function like document.getThumbnail() or window.render() that return a PNG of the html document.

回答1:

There are three different APIs that I can recommend:

  1. If you are willing to run a headless instance of Chrome, you can call Page.captureScreenshot. (docs) and example code
  2. If you are running inside as a browser extension, you can use the chrome.desktopCapture or visibleCapture API. (docs) and example code
  3. If you want to do this in plan JS, you can use html2canvas which lets you convert HTML dom to a canvas view, which you can then export and save as a file. However, the screenshots are not necessarily accurate:

    This script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.



回答2:

<html>
    <head>
      <script src="https://code.jquery.com/jquery-3.2.1.slim.js" integrity="sha256-tA8y0XqiwnpwmOIl3SGAcFl2RvxHjA8qp0+1uCGmRmg="
        crossorigin="anonymous"></script>
      <script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"></script>
    </head>
    <body>
      <div id="container" style="background-color: aliceblue; max-width:400px;">
        <h3>
          What is Lorem Ipsum?
        </h3>
        <hr />
        <p>
          Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy
          text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
          It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
          with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
      </div>
      <br/>
      <h3>SnapShot :</h3>
      <span id="previewImage"></span>
      <script>
        $(document).ready(function () {
          var element = $("#container");
          var getCanvas;
          html2canvas(element, {
            onrendered: function (canvas) {
              $("#previewImage").append(canvas);
              getCanvas = canvas;
            }
          });
        });
      </script>
    </body>
    </html>