jquery.qrcode 生成二维码

识别字符串

一、首先下载 jquery.qrcode 插件后,在页面中引入 jquery 库文件和 qrcode 插件。javascript

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

二、在页面中须要显示二维码的地方加入标签:html

<div id="qrcode" style="text-align: center;"></div> 

三、调用 qrcode 插件。html5

qrcode 支持 canvas 和 table 两种方式进行图片渲染,默认使用 canvas 方式,效率最高,固然要浏览器支持html5。调用以下:java

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

也能够经过如下方式调用:jquery

$("#qrcode").qrcode({ 
    render: "table"//table方式 
    width: 200//宽度 
    height:200//高度 
    text: "www.baidu.com" //任意内容 
}); 

这样就能够在页面中生成一个二维码。接下来就能够用手机“扫一扫”功能读取二维码信息。git

识别中文

咱们试验的时候发现不能识别中文内容的二维码,经过查找多方资料了解到,jquery-qrcode 是采用charCodeAt() 方式进行编码转换的。而这个方法默认会获取它的 Unicode 编码,若是有中文内容,在生成二维码前就要把字符串转换成 UTF-8,而后再生成二维码。您能够经过如下函数来转换中文字符串:github

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;    
} 

如下示例:canvas

var str = toUtf8("中文二维码!"); 
$('#qrcode').qrcode(str); 


ps:浏览器

jquery.qrcode.min.js 下载地址
函数

https://github.com/jack0888/jquery-qrcode

https://github.com/jeromeetienne/jquery-qrcode

相关文章
相关标签/搜索