html2canvas經過獲取頁面的DOM和元素的樣式信息,並將其渲染成canvas圖片,從而實現給頁面截圖的功能。javascript
由於每一個瀏覽器渲染頁面的方式都不盡相同,因此生成的圖片也不太同樣。html
環境要求: jQuery
兼容性: Firefox 3.5+, Chrome, Opera, IE9html5
官網主頁: http://html2canvas.hertzen.com/java
測試生成的圖片效果,有些元素的樣式沒有徹底展現出來jquery
測試代碼:web
<!DOCTYPE html> <html> <head> <meta name="layout" content="main"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script> <script type="text/javascript" > $(document).ready( function(){ $(".example1").on("click", function(event) { event.preventDefault(); html2canvas(document.body, { allowTaint: true, taintTest: false, onrendered: function(canvas) { canvas.id = "mycanvas"; //document.body.appendChild(canvas); //生成base64圖片數據 var dataUrl = canvas.toDataURL(); var newImg = document.createElement("img"); newImg.src = dataUrl; document.body.appendChild(newImg); } }); }); }); </script> </head> <body> Hello! <div class="" style="background-color: #abc;"> 計算機天堂測試html5頁面截圖 <br>jsjtt.com </div> <textArea id="textArea" col="20" rows="10" ></textArea> <input class="example1" type="button" value="button"> 生成界面以下: </body> </html>
說明在測試過程當中出現的問題若是頁面上引用跨域的圖片文件調用toDataURL的時候會出錯ajax
SecurityError: The operation is insecure. canvas
解決方法:在跨域的服務器上設置header設置爲容許跨域請求api
access-control-allow-origin: * access-control-allow-credentials: true
本文轉自:http://www.jsjtt.com/webkaifa/html5/2013-10-29/42.html跨域