html2canvas 可以通过纯JS对浏览器网页进行截屏,但截图的精确度还有待提高
官网: http://html2canvas.hertzen.com/
gitHub: https://github.com/niklasvh/html2canvas
引用 : <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
使用如下:具体详解 请查阅官方文档
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>网页DOM元素截图</title> <script type='text/javascript' th:src='@{/js/jquery-3.2.0.min.js}'></script> <script type='text/javascript' th:src='@{/js/screenshot/html2canvas.js}'></script> </head> <script type="text/javascript"> $(function () { $('#btn').click(function () { //#proMain:要截图的DOM元素 //useCORS:true:解决跨域问题 html2canvas(document.querySelector('#cut'), {useCORS: true}).then(function (canvas) { //获取年月日作为文件名 var timers = new Date(); var fullYear = timers.getFullYear(); var month = timers.getMonth() + 1; var date = timers.getDate(); var randoms = Math.random() + ''; //年月日加上随机数 var numberFileName = fullYear + '' + month + date + randoms.slice(3, 10); var imgData = canvas.toDataURL("image/png"); //保存图片 var saveFile = function (data, filename) { /* var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event);*/ /*--------------------------------------------------------方式二----------------------------------------------------*/ let triggerDownload = $("<a>").attr("href", data).attr("download", filename).appendTo("body"); triggerDownload[0].click(); triggerDownload.remove(); }; //最终文件名+文件格式 var filename = numberFileName + '.png'; // 下载图片(保存图片) saveFile(imgData, filename); // 把截的图显示在网页上 var img = document.createElement('img');//创建一个标签 img.setAttribute('src', imgData);//给标签定义src链接 document.getElementById('box').appendChild(img); }) }) // 代理事件(append之后的标签无法设置事件) $('#box').on('click', function (e) { var target = e.target || e.srcElement;//获取当前点击的对象 console.log(target.src) $('.bigImg').attr('src', target.src); $('.bigImg').css('display', 'block') }); }); </script> <body> <button id="btn">截图</button> <fieldset> <legend>显示图片</legend> <div id="box"></div> </fieldset> <div id="cut" style="height: 300px;width: 300px;border: 1px solid red;text-align: center;"> <h1>ABC</h1> </div> </body> </html>