網頁div轉換成圖片匯出——html2canvas
阿新 • • 發佈:2019-02-08
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <!--此網頁演示了html2canvas網頁截圖下載 -->
- <head>
- <!-- jquery庫和html2canvas庫 -->
- <scripttype="text/javascript"src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
- <script
- <title>html2canvas網頁截圖</title>
- <!--需要注意的是,這裡一定要等待js庫和網頁載入完畢後再執行函式 -->
- <!-- html2canvas()中,第一個引數是要截圖的Dom物件,第二個引數時渲染完成後回撥的canvas物件。 -->
- <scripttype="text/javascript"
- $(function(){
- print();
- });
- function print(){
- html2canvas( $("#canv") ,{
- onrendered: function(canvas){
- $('#down_button').attr( 'href' , canvas.toDataURL() ) ;
- $('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
- }
- });
- }
- </script>
- <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
- </head>
- <body>
- <divid="canv">
- Cease to struggle and you cease to live.<br/>
- </div>
- <atype="button"id="down_button">download</a>
- </body>
- </html>
以上為html2canvas的一個小demo,可以將id為canv的div轉換成圖片並下載。
實際操作中以上程式碼只能轉換顯示器解析度大小的網頁圖片,對於高度超過螢幕解析度高度的網頁不能全部匯出。
經過測試,在第二個引數中加入高度即可將指定高度的網頁匯出為圖片,程式碼如下:
- function print(){
- html2canvas( $("#canv") ,{
- onrendered: function(canvas){
- $('#down_button').attr( 'href' , canvas.toDataURL() ) ;
- $('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
- },
- height:9000
- });
- }