html2canvas 實現網頁截圖
阿新 • • 發佈:2018-12-14
html2canvas可以通過純JS對瀏覽器網頁進行截圖,但截圖的精確度還有待提高
引用 : <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
主要用法是:
html2canvas(document.getElementById('view'), { onrendered: function(canvas) { document.body.appendChild(canvas);
// console.log(canvas.toDataURL()); }, // width: 300, // height: 300 });
這是一個demo
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>html2canvas example</title> <style> #view{ border: 1px solid red; background-image: url(image/c05ddd91c8803ea8306f02cf4a10fcdb.png); background-size: 100%; width: 100px; height: 100px; } </style> </head> <body> <div id="view"> <input type="button" value="截圖" onclick="takePhoto()"> </div> </body> <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script> <script type="text/javascript"> function takePhoto() { html2canvas(document.getElementById('view'), { onrendered: function(canvas) { console.log(canvas.toDataURL());//這是截圖的base64 document.body.appendChild(canvas);//這是有截圖的畫布 }, }); } </script> </html>
執行之後:
點選截圖按鈕:
下面出現的就是截圖,不過不太清楚。