首先下载jquery.qrcode.js
或者qrcode.js
引入需要的文件:jquery.min.js
和jquery.qrcode.js
html部分:
<div class="demo">
<p>请输入内容然后提交生成二维码:</p>
<p>
<input type="text" class="input" id="mytxt" value="">
<input type="button" id="sub_btn" value="提交">
</p>
<div id="code"></div>
</div>
Js部分
$("#sub_btn").click(function () {
$("#code").empty();
var str = $("#mytxt").val();
str = toUtf8(str);
var qrcode = $("#code").qrcode({
render: "canvas",
width: 200,
height: 200,
text: str
});
//base64文件流图片;
qrcode.hide();
var canvas = qrcode.find('canvas').get(0);
var src = canvas.toDataURL('image/png',1);
});
//转汉字
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;
}
以上是以 js 部分直接实现,但是在二维码中间加 logo 时处理起来就非常的麻烦了,然后就重新构建了新的生成方法,详见下篇文章。