使用jquery.qrcode生成二維碼

 

二維碼應用已經滲透到咱們的生活工做當中,您只須要用手機對着二維碼「掃一掃」便可得到所對應的信息,方便咱們瞭解商家、購物、觀影等等。本文將介紹一款基於jquery的二維碼生成插件qrcode,在頁面中調用該插件就能生成對應的二維碼。 文章來自:helloweba.com  下載源代碼頁面:http://www.helloweba.com/view-blog-226.htmljavascript

qrcode實際上是經過使用jQuery實現圖形渲染,畫圖,支持canvas(HTML5)和table兩種方式,您能夠到https://github.com/jeromeetienne/jquery-qrcode獲取最新的代碼。html

如何使用

一、首先在頁面中加入jquery庫文件和qrcode插件。html5

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript" src="jquery.qrcode.min.js"></script> 

二、在頁面中須要顯示二維碼的地方加入如下代碼:java

<div id="code"></div>  

三、調用qrcode插件。jquery

qrcode支持canvas和table兩種方式進行圖片渲染,默認使用canvas方式,效率最高,固然要瀏覽器支持html5。直接調用以下:git

$('#code').qrcode("http://www.helloweba.com"); //任意字符串  

您也能夠經過如下方式調用:github

$("#code").qrcode({    
  render: "table", //table方式    
  width: 200, //寬度    
  height:200, //高度    
  text: "www.helloweba.com" //任意內容  }); 

這樣就能夠在頁面中直接生成一個二維碼,你能夠用手機「掃一掃」功能讀取二維碼信息。web

識別中文

咱們試驗的時候發現不能識別中文內容的二維碼,經過查找多方資料瞭解到,jquery-qrcode是採用charCodeAt()方式進行編碼轉換的。而這個方法默認會獲取它的Unicode編碼,若是有中文內容,在生成二維碼前就要把字符串轉換成UTF-8,而後再生成二維碼。您能夠經過如下函數來轉換中文字符串:canvas

function toUtf8(str) {    
    var out, i, len, c;    
    out = "";    
    len = str.length;      
   for(i = 0; i < len; i++) {    
        c = str.charCodeAt(i);        
     if ((c >= 0x0001) && (c <= 0x007F)) {       
          out += str.charAt(i);         
    else if (c > 0x07FF) {           
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));    
            out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));         
        out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));          
   else {       
          out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));           
      out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));            
 }      
   }    
    return out;    

如下示例:瀏覽器

var str = toUtf8("釣魚島是中國的!");  $('#code').qrcode(str);  
 

相關文章
相關標籤/搜索