1. 程式人生 > 實用技巧 >JS(一) QRCode 生成和下載二維碼

JS(一) QRCode 生成和下載二維碼

  1. 引入外掛QRCode QRCode.js 是一個用於生成二維碼的 JavaScript 庫。主要是通過獲取 DOM 的標籤,再通過 HTML5 Canvas 繪製而成,不依賴任何庫。
    (偷懶連結)
    https://static.runoob.com/download/qrcodejs-04f46c6.zip
  2. 基本使用
    <div id="qrcode"></div>
    var qrcode = new QRCode(document.getElementById("qrcode"), "http://www.runoob.com"); // 設定要生成二維碼的連結
    qrcode.makeCode();     // 生成二維碼
    ......
    qrcode.clear();        //清除二維碼
  3. 使用注意事項:
    • url必須帶通訊協議
    • 生成二維碼前必須先清空二維碼,不然會重複生成二維碼
      • document.getElementById("qrcode").innerHTML = "";
      • 或者利用全域性變數儲存對QRCode的引用,每次生成時判空,非空使用qrcode.clear()清除二維碼,重新生成二維碼

   

<html>
	<head>
		<meta charset="utf-8">
		<title>生成和下載二維碼</title>
		<!-- 引入QRCode -->
		<script src="qrcodejs-04f46c6/qrcode.min.js"></script>
		<script src="qrcodejs-04f46c6/jquery.min.js"></script>
	</head>
	<body>
		<button id="p1">點選生成二維碼</button>
		<button id="p2">下載二維碼</button>
		<a id="downloadLink" style="display: none;"></a>
		<!-- 顯示二維碼區域 -->
		<div id="qrcode" style="width:100px; height:100px; margin-top:15px;"></div>
		<script type="application/javascript">
			$("#p1").click(function() {
				// 避免因多次點選生成多個二維碼
				document.getElementById("qrcode").innerHTML = "";
				// 二維碼掃描後跳轉介面
				var url = "http://www.baidu.com";	// 必須新增訪問url的http協議,否則顯示字串
				// 寫法一
				var qrcode = new QRCode(document.getElementById("qrcode"), {
					// 二維碼基本引數
					text: "http://www.baidu.com",		//	url
					width: 128,			// 寬度(百分比 no)
					height: 128,		// 高度(百分比 no)
					colorDark : "#000000",	// 生成的二維碼的深色部分
					colorLight : "#ffffff",	// 生成二維碼的淺色部分
					correctLevel : QRCode.CorrectLevel.H	// 容錯級別
					background : "#ffffff",//背景顏色  
					foreground : "#000000",//前景顏色
					src : '../img/pm.jpg'  //二維碼中間的圖片
				});
				// 生成二維碼
				qrcode.makeCode(url);
				
				
				/* // 寫法二
				var qrcode = new QRCode(document.getElementById("qrcode"), {
					text: "http://www.baidu.com",		//	url
					width: 128,			// 寬度(百分比 no)
					height: 128,		// 高度(百分比 no)
					colorDark : "#000000",	// 生成的二維碼的深色部分
					colorLight : "#ffffff",	// 生成二維碼的淺色部分
					correctLevel : QRCode.CorrectLevel.H	// 容錯級別
					background : "#ffffff",//背景顏色  
					foreground : "#000000",//前景顏色
					src : '../img/pm.jpg'  //二維碼中間的圖片
				});
				qrcode.makeCode(); 
				*/
			});
			
			$("#p2").click(function() {
				var name= "QRcode";
				// 獲取base64的圖片節點
				var img = document.getElementById('qrcode').getElementsByTagName('img')[0];	
				// 構建畫布
				var canvas = document.createElement('canvas');
				canvas.width = img.width;
				canvas.height = img.height;
				canvas.getContext('2d').drawImage(img, 0, 0);
				// 構造url
				url = canvas.toDataURL('image/png');
				// 構造a標籤並模擬點選
				var downloadLink = document.getElementById('downloadLink');
				downloadLink.setAttribute('href', url);
				downloadLink.setAttribute('download', name+'.png');
				downloadLink.click();
			  });
		</script>
	</body>
</html>