利用html2canvas将html页面截图 js
在截图页面引入html2canvas.js
下载地址: http://www.bootcdn.cn/html2canvas/
demo页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>htmltopic</title> <script type="text/javascript" src="~/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="~/js/html2canvas.min.js"></script> <style> * { margin: 0; } .test { width: 100px; height: 100px; text-align: center; line-height: 100px; background-color: #87CEEB; display: inline-block; vertical-align: top; } canvas { margin-right: 5px; } .down { float: left; margin: 40px 10px; } .down2 { float: left; margin: 40px 30px; } </style> </head> <body> <div class="test">测试</div> <div> <a class="down" href="" download="downImg">下载</a> </div> </body> </html>
js方法:
function SetCanvas() { //滚动条置顶, 避免截图不全 window.pageYoffset = 0; document.documentElement.scrollTop = 0; document.body.scrollTop = 0; //定义画布容器 var canvas2 = document.createElement("canvas"); let _canvas = document.querySelector('div');//画布大小 var w = parseInt(window.getComputedStyle(_canvas).width); var h = parseInt(window.getComputedStyle(_canvas).height); //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了 canvas2.width = w * 2; canvas2.height = h * 2; canvas2.style.width = w + "px"; canvas2.style.height = h + "px"; //可以按照自己的需求,对context的参数修改,translate指的是偏移量 // context.translate(0,0); var context = canvas2.getContext("2d"); context.scale(2, 2); html2canvas(document.querySelector('.gMain'), { canvas: canvas2 }).then(function (canvas) { //document.body.appendChild(canvas); //canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载 document.querySelector(".down").setAttribute('href', canvas.toDataURL()); }); }
html2canvas根据body进行截图,若内容高度高于body时,
页面很长(伴有滚动条),只能截取到当前区域,会出现截图不全的问题。
使用以下方法:
window.pageYoffset = 0;
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
在生成截图前,把滚动条置顶即可避免截图不全!!!
参考:https://blog.csdn.net/huwei2003/article/details/79761580
https://www.cnblogs.com/xingzoudecd/p/12603632.html