首页 > web前端 > js教程 > 正文

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

WBOY
发布: 2016-05-16 16:40:12
原创
1927 人浏览过

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 &#63; 0 : 1][i < tdLen &#63; 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函数

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!