<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>生成二维码并且下载为图片文件</title> <!-- 去这里下载 https://github.com/tsayen/dom-to-image/edit/master/src/dom-to-image.js--> <script type="text/javascript" src="dom-to-image.js"></script> <!-- 去这里下载 https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js--> <script type="text/javascript" src="FileSaver.js"></script> <!-- 去这里下载 https://github.com/davidshimjs/qrcodejs/blob/master/qrcode.js--> <script type="text/javascript" src="qrcode.js"></script> <style> /*必须设置二维码的宽高,否则 呵呵哒~*/ #qrcode-file { width: 400px; height: 500px; } #qrcode-img { margin: 50px; } #qrcode-text { width: 100%; text-align: center; font-size: 30px; } </style> </head> <body> <div id="qrcode-file"> <div id="qrcode-img"></div> <h1 id="qrcode-text">二维码名称</h1> </div> <button style="font-size: 30px;">下载二维码</button> </body> </html> <!--核心代码在这里--> <script type="text/javascript"> //强哥的二维码方法---------------------------------------- var sgQrCode = { createQrcode: function (o) { /*先生成二维码*/ new QRCode(document.querySelector("#qrcode-img"), { text: o.url, width: 300, height: 308, colorDark: "#000000", colorLight: "#ffffff", correctLevel: QRCode.CorrectLevel.H }); document.querySelector("#qrcode-text").innerHTML = o.text; // qrcode.clear(); // 清除二维码 // qrcode.makeCode("http://www.s-zq.com"); // 生成其他二维码快捷调用 }, download: function (o) { domtoimage.toBlob(document.querySelector("#qrcode-file")) .then(function (blob) { window.saveAs(blob, o.fileName + ".png"); }); } }; //---------------------------------------- sgQrCode.createQrcode({url: "http://www.shuzhiqiang.com", text: "强哥的个人网站二维码"});//生成二维码 document.querySelector("button").onclick = function () { sgQrCode.download({fileName: this.innerText});//下载二维码 }; </script>