二维码应用已经渗透到咱们的生活工做当中,您只须要用手机对着二维码“扫一扫”便可得到所对应的信息,方便咱们了解商家、购物、观影等等。本文将介绍一款基于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);