实现原理是通过canvas利用input的value值在div内生成canvas绘制的二维码,然后toDataURL方法为img赋值最终实现二维码的生成和下载
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>收款二维码</title>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div style="text-align: center;display: none" id="qrPic"></div>
<input type="hidden" id="codeUrl" name="codeUrl" value="jebchjebch" />
<img src="" id="myImg"/>
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script src="jquery.qCode.min.js"></script>
<script type="text/javascript">
$(function() {
qr();
});
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.fromCcodeharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
//生成二维码代码
function qr() {
$("#qrPic").empty();
var str = toUtf8($("#codeUrl").val());
$("#qrPic").qrcode({
render: "canvas",
width: 270,
height: 270,
text: str
});
$("canvas").attr("id", "erw");
var canvas = document.getElementById('erw');
var context = canvas.getContext('2d');
var strDataURI = canvas.toDataURL();
document.getElementById('myImg').src = strDataURI;
console.log(strDataURI)//可以得到url
}
</script>
</body>
</html>