生成二维码的 jQuery 插件:jquery.qrcode.js

jquery.qrcode.js 是一个纯浏览器 生成 QRcode 的 jQuery 插件,它使用非常简单,生成的 QRcode 无需下载图片,并且不依赖第三方服务,比如最近 Google 服务在国内访问不稳就造成我好几个网站的 QRcode 不能使用,并且压缩之后大小小于 4K。

jquery.qrcode.js 使用

1. 加载 jQuery 和 jquery.qrcode.js:

<script type='text/javascript' src='http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js'></script>
<script type="text/javascript" src="http://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>

2. 创建一个用于包含 QRcode 图片的 DOM 元素,比如 div:

<div id="qrcode"></div>

3. 然后通过下面代码生成 QRcode:

jQuery('#qrcode').qrcode("http://blog.wpjam.com");

4. 默认生成的二维码大小是 256×256,当然可以自定义大小:

jQuery('#qrcode').qrcode({width: 64,height: 64,text: "http://blog.wpjam.com"});

原文:http://blog.wpjam.com/m/jquery-qrcode/

github地址:https://github.com/lrsjng/jquery-qrcode

官方文档地址:http://larsjung.de/jquery-qrcode/

下载附件:jquery-qrcode-master

 

options可定制render的方式,大小,颜色等信息:

{
    // render 方式: 'canvas', 'image' or 'div'
    render: 'canvas',

    // version range somewhere in 1 .. 40
    minVersion: 1,
    maxVersion: 40,

    // error correction level: 'L', 'M', 'Q' or 'H'
    ecLevel: 'L',

    // offset in pixel if drawn onto existing canvas
    left: 0,
    top: 0,

    // size in pixel
    size: 200,

    // code color or image element
    fill: '#000',

    // background color or image element, null for transparent background
    background: null,

    // content
    text: 'no text',

    // corner radius relative to module width: 0.0 .. 0.5
    radius: 0,

    // quiet zone in modules
    quiet: 0,

    // modes
    // 0: normal
    // 1: label strip
    // 2: label box
    // 3: image strip
    // 4: image box
    mode: 0,

    mSize: 0.1,
    mPosX: 0.5,
    mPosY: 0.5,

    label: 'no label',
    fontname: 'sans',
    fontcolor: '#000',

    image: null
}

 

识别中文

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

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

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.