zoukankan      html  css  js  c++  java
  • 网页div转换成图片导出——html2canvas

    [html] view plain copy
    1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    2. <html>  
    3.     <!--此网页演示了html2canvas网页截图下载 -->     
    4.     <head>  
    5.         <!-- jquery库和html2canvas库 -->  
    6.         <script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>  
    7.         <script type="text/javascript" src="http://www.boolaw.com/tpl/default/js/jquery-1.8.3.min.js"></script>  
    8.         <title>html2canvas网页截图</title>  
    9.       
    10.         <!--需要注意的是,这里一定要等待js库和网页加载完毕后再执行函数  -->  
    11.         <!-- html2canvas()中,第一个参数是要截图的Dom对象,第二个参数时渲染完成后回调的canvas对象。  -->        
    12.         <script type="text/javascript">  
    13.             $(function(){     
    14.                 print();  
    15.             });  
    16.             function print(){     
    17.                 html2canvas( $("#canv") ,{            
    18.                     onrendered: function(canvas){  
    19.                         $('#down_button').attr( 'href' , canvas.toDataURL() ) ;  
    20.                         $('#down_button').attr( 'download' , 'myjobdeer.png' ) ;  
    21.                     }  
    22.                 });  
    23.             }  
    24.         </script>  
    25.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    26.     </head>  
    27.     <body>  
    28.         <div id="canv">  
    29.         Cease to struggle and you cease to live.<br/>  
    30.   
    31.         </div>  
    32.         <a type="button" id="down_button">download</a>  
    33.       
    34.     </body>  
    35. </html>  

    以上为html2canvas的一个小demo,可以将id为canv的div转换成图片并下载。

    实际操作中以上代码只能转换显示器分辨率大小的网页图片,对于高度超过屏幕分辨率高度的网页不能全部导出。

    经过测试,在第二个参数中加入高度即可将指定高度的网页导出为图片,代码如下:

    [html] view plain copy
    1. function print(){  
    2.         html2canvas( $("#canv") ,{            
    3.             onrendered: function(canvas){  
    4.                 $('#down_button').attr( 'href' , canvas.toDataURL() ) ;  
    5.                 $('#down_button').attr( 'download' , 'myjobdeer.png' ) ;  
    6.             },  
    7.         height:9000  
    8.         });  
    9.     }  
  • 相关阅读:
    进程通信
    python模块成像库pillow
    python模块IO
    python模块StringIO和BytesIO
    DJango重写用户模型
    DJango模型Meta选项详解
    DJango中事务的使用
    批量删除文件
    批量修改文件名字或后缀
    自定义中间件实现插拔设计
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13317522.html
Copyright © 2011-2022 走看看