使用jquery.qrcode生成彩色二维码实例


jquery.qrcode.js 是居于jquery类库的绘制二维码的插件,用它来实现二维码图形渲染支持canvas和table两种绘图方式。(jquery.qrcode.js 设置显示方式为table时在webkit核心浏览器如chrome下会变形,这个需要注意。)

下面为测试代码(增加了颜色控制,可以设置4个区块的颜色值,需要指定render为table。),效果如下:

代码如下:

<html>
<head>
<title>JS生成二维码</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.qrcode.min.js"></script>
<style>
 #output{
 margin-left:300px; 
 margin-top:100px; 
 }
</style>
</head>
<body>
<div id="output"></div>
<script>
 window.onload = function () {
 var trs = $('#output').qrcode({
  width: 100,
  height: 100,
  render: "canvas", //设置渲染方式 table canvas
  text: utf16to8("javascript生成二维码"),
  background: "#ffffff", //背景颜色 
  foreground: "red" //前景颜色 
 }).find('tr'), trLen = Math.floor(trs.size() / 2), tdLen = Math.floor(trs.eq(0).find('td').size() / 2), tds, bgColor;
 var colors = [['#ff0000', '#0100e2'], ['#00ed01', '#9f4d95']];
 trs.each(function (j) {
  tds = $(this).find('td');
  tds.each(function (i) {
  bgColor = this.style.backgroundColor;
  if (bgColor == 'red') {
   this.style.backgroundColor = colors[j < trLen ? 0 : 1][i < tdLen ? 0 : 1];
  }
  });
 });
 }
 function utf16to8(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;
 } 
</script>
 
</body>
</html>

jquery-qrcode这个库是采用 charCodeAt这个方式进行编码转换的,而这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式,英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。
 
解决方式:在二维码编码前把字符串转换成UTF-8,具体代码如上utf16to8函数

PS:本站还提供了一个功能非常强大的二维码生成工具,感兴趣的朋友可以参考一下:

http://tools.phpstudy.net/transcoding/phpstudyqrcode


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3