月度归档: 2016 年 2 月

  • 使用JavaScript库jQuery.qrcode生成二维码

    在线二维码生成器

    使用开源二维码库 jquery.qrcode.js (https://github.com/jeromeetienne/jquery-qrcode)在浏览器上直接生成二维码,不需要后端程序支持。该库对中文不友好。

    生成二维码

    $('#qrcode')
    	.empty(()
    	.qrcode({
    		render: window.CanvasPattern ? 'canvas' : 'table',
    		width: 300,
    		height: 300,
    		text: 'blog.zhengxianjun.com'
    	});

    jquery.qrcode 核心是 qrcode.js,jquery.qrcode.js 将其封装成了 jQuery 扩展,封装代码很少。以表格 table 模式可以使在不支持 canvas 的浏览器下也能正常运行。

    二维码配置

    var options = {
    	render        : "canvas", // 渲染方式 table|canvas
    	width         : 256, // 二维码宽度
    	height        : 256, // 二维码高度
    	typeNumber    : -1, // 计算模式
    	correctLevel  : QRErrorCorrectLevel.H, // 纠错等级
    	background    : "#ffffff", // 背景色
    	foreground    : "#000000" // 前景色
    };

    中文二维码

    jquery.qrcode 使用 charCodeAt 转码,charCodeAt 使用的 2 位的 Unicode 编码,中文字符采用 3 位的 UTF8 编码,两者长度不匹配,导致生成二维码的源字符流有误。

    需要先将 UTF16 转 UTF8,实现来自 http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

    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;
    }
  • 微信 WebView User-Agent

    Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12H143 MicroMessenger/6.2.2 NetType/WIFI Language/zh_CN