这里有新鲜出炉的 jQuery 示例,程序狗速度看过来!
jQuery 是一个兼容多浏览器的 javascript 框架,核心理念是 write less,do more(写得更少, 做得更多)。jQuery 在 2006 年 1 月由美国人 John Resig 在纽约的 barcamp 发布,吸引了来自世界各地的众多 JavaScript 高手加入,由 Dave Methvin 率领团队进行开发。
这篇文章主要介绍了使用 jquery.qrcode 生成彩色二维码实例, jquery.qrcode 是一个 jquery 的插件, 需要的朋友可以参考下
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://www.phperz.com/article/17/0713/275149.html