總的有兩個依賴, jquery和jquery.qrcode 。實現原理其實就是圖層的堆疊。做二維碼推廣的時候要用到此方法
<body> <div class="" id="qrcode" style="display: none;"></div> <canvas id="sec_canvas" ></canvas> <img id="bg_pic" src="/pic/tgdt1.jpg" /> <img class="canimg" /> </body> <script type="text/javascript"> //獲取可顯示區域的寬和高 var width = $('.user_cont').width(); //寬度 var height = $('.user_cont').height(); // 高度 //設置底圖顯示大小 var bg_pic = document.getElementById("bg_pic"); bg_pic.style.width = width+'px'; bg_pic.style.height = height+'px'; //先把二維碼內容畫出來,不然等下太慢了 new QRCode(document.getElementById("qrcode"), { text: location.origin+'?dl='+sessionStorage.getItem('id'), width: 800, height: 800 }); //獲取二維碼圖片 var qr_canvas1=document.getElementsByTagName('canvas')[0]; var image = new Image(); image.src = qr_canvas1.toDataURL("image/png"); //因爲是要在背景圖上畫東西,所以要等背景圖加載完成後才能繼續下一步 bg_pic.onload = function() { //必須等待圖片加載完成 //弄張畫布出來 var c = document.getElementById("sec_canvas"); c.width = width c.height = height //獲取畫布,然後就可以開始畫了 var ctx = c.getContext("2d"); //先把背景圖先畫上去 { ctx.drawImage(bg_pic, 0, 0, width, height); //繪製圖像進行拉伸 } //畫二維碼 { //要等二維碼的圖片生成後才能畫 ,如果畫出來的是空白,可以能是圖片還沒生產好可以使用onload方法 //img.onload = function() {} ctx.drawImage(image, width*0.3, height*0.69, width*0.4, height*0.225); } { //寫點文字上去 ctx.font = 'bold '+height*0.028+'px sans-serif'; ctx.fillStyle = '#fcde04'; ctx.fillText('【長按】保存/轉發', width*0.25, height*0.96); } //繪製完成,轉爲圖片 setTimeout(function() { //在ios上無法在畫完之後取到整個畫布內容,加了個settimeout var bigcan = $('canvas')[0]; let images = new Image(); images.src = bigcan.toDataURL("image/png"); //alert(bigcan.toDataURL("image/png")) images.setAttribute("crossOrigin", 'Anonymous') { var cc1=document.getElementsByTagName('canvas')[1]; cc1.toDataURL("image/png"); $('.canimg').css('width', width); $('.canimg').css('height', height); $('.canimg').attr('src', cc1.toDataURL("image/png")); //圖畫好,畫圖過程使用的墊子全部都要隱藏起來 c.style.display = 'none'; bg_pic.style.display = 'none'; } }, 0 ) } </script>