1、需要生成图片的页面引入JS【html2canvas.js自行到官网下载即可】
<script src="/js/html2canvas.js"></script>
2、demo页面【H5页面】
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>PHP 将页面生成图片Demo样例-wpl</title> <script src="/js/jquery-1.10.1.min.js"></script> <script src="/js/html2canvas.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> <!--页面最终生成的图片--> <img src="" alt="" id="predict_img"> <!--<input type="file" style="/* visibility: hidden */" capture="camera" accept="image/*,video/*" name="" value="" οnclick="openCamera()">--> <button id="upload_img_but">选择照片</button> <script> //直接选择要截图的dom,就能截图,但是因为canvas的原因,生成的图片模糊 //html2canvas(document.querySelector('div')).then(function(canvas) { // document.body.appendChild(canvas); //}); //创建一个新的canvas 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指的是偏移量 // var context = canvas.getContext("2d"); // context.translate(0,0); var context = canvas2.getContext("2d"); context.scale(2, 2); html2canvas(document.querySelector('div'), { canvas: canvas2 }).then(function(canvas) { // document.body.appendChild(canvas); //canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载 // document.querySelector(".down").setAttribute('href', canvas.toDataURL()); // $("#predict_img").attr("src",canvas.toDataURL()); getBase64Image(canvas.toDataURL()); }); function getBase64Image(imgurl) { var img = new Image(); img.src = imgurl; img.setAttribute('crossOrigin', 'anonymous'); img.οnlοad=function(){ var canvas = document.createElement("canvas"); canvas.width = 300;//这个设置不能丢,否者会成为canvas默认的300*150的大小 canvas.height = 300;//这个设置不能丢,否者会成为canvas默认的300*150的大小 var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, 300, 300); var dataURL = canvas.toDataURL("image/png"); // console.log(dataURL); $("#predict_img").attr("src",dataURL); // html2img(); } } </script> </body> </html>