2017-07-03 73 views
1

是否可以使用javascript获取html文档的图像。我正在寻找一个像document.getThumbnail()window.render()这样的javascript函数,它返回一个html文档的PNG渲染HTML文档缩略图

回答

1

有三种不同的API,我可以推荐:

  1. 如果你愿意运行Chrome浏览器一具无头的实例,就可以调用Page.captureScreenshot。 (docs)和example code
  2. 如果您作为浏览器扩展运行,您可以使用chrome.desktopCapturevisibleCapture API。 (docs)和example code
  3. 如果要在计划JS中执行此操作,可以使用html2canvas,它可以将HTML dom转换为画布视图,然后可以将其导出并另存为文件。但是,屏幕截图不一定准确:

    该脚本允许您直接在用户浏览器上截取网页或网页的一部分。屏幕截图基于DOM,因此它可能不是100%准确的真实表示,因为它不会制作实际的屏幕截图,而是根据页面上提供的信息构建屏幕截图。

0
<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> 
+0

此代码把一个页面的内部的图像。显然,如果你想捕捉整个页面,在body标签中添加id =“container”。希望这有帮助 –