vue篇qrcode下载二维码
npm安装qrcode不用多说了,直接实例
html代码片段
<img src="" alt="" @error="getCode" style="opacity:0;width:0;" />
<div id="qrcode"></div> <div class="ii-btn" @click="loadCode">下载</div>
js代码片段
getCode(){ var qrcode = new QRCode('qrcode', { text: 'http://www.baidu.com', width: 100, height: 100, colorDark : '#000000', colorLight : '#ffffff', correctLevel : QRCode.CorrectLevel.H }) }, //base64转blob base64ToBlob(code) { let parts = code.split(";base64,"); let contentType = parts[0].split(":")[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }, //下载二维码 loadCode() { let img= document.querySelector("#qrcode img"); // // //创建一个a标签节点 let a = document.createElement("a"); // //设置a标签的href属性(将canvas变成png图片) let imgURL = img.getAttribute('src'); let ua = navigator.userAgent; if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且 windows系统 情况下 才执行; let bstr = atob(imgURL.split(",")[1]); let n = bstr.length; let u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } let blob = new Blob([u8arr]); window.navigator.msSaveOrOpenBlob(blob, "qrCode" + "." + "png"); } else if (ua.indexOf("Firefox") > -1) { //火狐兼容下载 let blob = this.base64ToBlob(imgURL); //new Blob([content]); let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为 a.download = " "; //下载图片名称,如果填内容识别不到,下载为未知文件,所以我这里就不填为空 a.href = URL.createObjectURL(blob); a.dispatchEvent( new MouseEvent("click", { bubbles: true, cancelable: true, view: window, }) ); //兼容火狐 } else { //谷歌兼容下载 img.src = img.getAttribute('src'); // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream') a.href = img.src; //设置下载文件的名字 // a.download = "qrCode"; a.download='people_code.png'; //点击 a.click(); } },
经过地狱般的磨练,创造出天堂的力量。流过血的手指,弹出世间的绝唱!