需求:1、移动端点击分享时,截屏当前屏幕,并保存为图片 2、将截屏的图片与一张二维码图片进行拼接后,生成一张新的图片
技术栈:html2canvas.js、canvas2image.js
代码:(jquery和原生js混写了,不是很规范)
<script type="text/javascript"> //获取页面中的分享按钮 var sharebtn = document.querySelectorAll('.share'); for(let i=0;i<sharebtn.length;i++){ //给分享按钮添加touch事件 sharebtn[i].ontouchend = function(){ //html2canvas语法,截取当前屏幕h5转为canvas html2canvas(document.body).then(canvas => { document.body.appendChild(canvas); var canvasbox = document.getElementsByTagName('canvas')[0]; var w = canvasbox.width,h = canvasbox.height; //canvas转化为图片并添加到body中,以便于第二次图片拼接时获取该图片 var img = Canvas2Image.convertToPNG(canvas, w, h); img.id = 'img1'; document.body.appendChild(img) //创建新画布并添加到body中 var canvasel = document.createElement('canvas'); canvasel.id = 'mycanvas'; canvasel.width = 750; canvasel.height = 1654; document.body.appendChild(canvasel); //当截屏的图片加载完成后,执行该方法 img.onload = function(){ //获取新画布 var mycanvas = document.getElementsByTagName('canvas')[1]; var w = mycanvas.width,h = mycanvas.height; var ctx = mycanvas.getContext('2d'); //创建需要拼接的二维码图片 var lastimg = new Image(); lastimg.src='image/ewm.png'; //获取截屏的图片 var img1 = document.getElementById('img1'); //当二维码图片加载完成后执行: lastimg.onload = function(){ //在新的canvas中绘制两张图片并将该canvas转化为图片 ctx.drawImage(img1,0,0); ctx.drawImage(lastimg,0,1334); var newimg = Canvas2Image.convertToPNG(mycanvas,w,h); //将图片添加到页面的结构中 并显示该结构 document.getElementById('imgbox').appendChild(newimg); $('.img-show-wrap').removeClass('hide'); $('.mask').removeClass('hide'); } } }) } } </script>