1. 程式人生 > >網頁div轉換成圖片匯出——html2canvas

網頁div轉換成圖片匯出——html2canvas

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3.     <!--此網頁演示了html2canvas網頁截圖下載 -->
  4.     <head>
  5.         <!-- jquery庫和html2canvas庫 -->
  6.         <scripttype="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.         <!--需要注意的是,這裡一定要等待js庫和網頁載入完畢後再執行函式  -->
  10.         <!-- html2canvas()中,第一個引數是要截圖的Dom物件,第二個引數時渲染完成後回撥的canvas物件。  -->
  11.         <scripttype="text/javascript"
    >
  12.             $(function(){     
  13.                 print();  
  14.             });  
  15.             function print(){     
  16.                 html2canvas( $("#canv") ,{            
  17.                     onrendered: function(canvas){  
  18.                         $('#down_button').attr( 'href' , canvas.toDataURL() ) ;  
  19.                         $('#down_button').attr( 'download' , 'myjobdeer.png' ) ;  
  20.                     }  
  21.                 });  
  22.             }  
  23.         </script>
  24.         <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
  25.     </head>
  26.     <body>
  27.         <divid="canv">
  28.         Cease to struggle and you cease to live.<br/>
  29.         </div>
  30.         <atype="button"id="down_button">download</a>
  31.     </body>
  32. </html>

以上為html2canvas的一個小demo,可以將id為canv的div轉換成圖片並下載。

實際操作中以上程式碼只能轉換顯示器解析度大小的網頁圖片,對於高度超過螢幕解析度高度的網頁不能全部匯出。

經過測試,在第二個引數中加入高度即可將指定高度的網頁匯出為圖片,程式碼如下:

  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.     }