html2canvas如何将div转成图片并下载,如何将滚动条的内容截取下来
<!DOCTYPE html> <html lang="en"> <head> <meta name="layout" content="main"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #canvs { background-color: yellow; width: 400px; margin: 100px auto; text-align: center; padding: 10px; } .title { font-size: 18px; } </style> <script type="text/javascript" src="http://www.boolaw.com/tpl/default/js/jquery-1.8.3.min.js"></script> <script type="text/javascript" src="js/html2canvas.js"></script> <script type="text/javascript"> function downloadForJS() { //使用html2canvas 转换html为canvas html2canvas(document.getElementById('canvs')).then(function (canvas) { var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url var saveLink = document.createElement('a'); saveLink.href = imgUri; saveLink.download = 'downLoad.png'; saveLink.click(); }); } </script> </head> <body> <div id="canvs"> <div class="title">如梦令·昨夜雨疏风骤</div> <div>[宋] 李清照</div> <div>昨夜雨疏风骤,浓睡不消残酒,试问卷帘人,却道海棠依旧。</div> <div>知否,知否,应是绿肥红瘦。</div> </div> <div style="width: 400px;margin:50px auto;"> <input class="button" type="button" value="button" onclick="downloadForJS()">测试</input> </div> </body> </html>
2.如果存在滚动条,怎么把滚动条里面的内容也截取下来
downloadForJS() { var targetDom = this.common.getClass('div', 'rightBox')[0] var copyDom = targetDom.cloneNode(true) // 克隆节点 copyDom.style.width = targetDom.offsetWidth + 'px' copyDom.style.height = targetDom.scrollHeight + 'PX' // 获得高度 document.getElementsByClassName('wrapperRight')[0].appendChild(copyDom) // 插入节点 html2canvas(copyDom).then((canvas) => { document.getElementsByClassName('wrapperRight')[0].removeChild(copyDom) // 删除节点 var imgUri = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream') // 获取生成的图片的url var saveLink = document.createElement('a') saveLink.href = imgUri saveLink.download = 'downLoad.png' saveLink.click() }) }
亦心晗