zoukankan      html  css  js  c++  java
  • 使用jquery-qrcode生成二维码(转载)

    一、使用jquery-qrcode生成二维码

    先简单说一下jquery-qrcode,这个开源的三方库(可以从https://github.com/jeromeetienne/jquery-qrcode 获取),

    qrcode.js 是实现二维码数据计算的核心类,

    jquery.qrcode.js 是把它用jquery方式封装起来的,用它来实现图形渲染,其实就是画图(支持canvas和table两种方式)

    支持的功能主要有:

    1. text     : "https://github.com/jeromeetienne/jquery-qrcode"  //设置二维码内容  
    1. render   : "canvas",//设置渲染方式  
    2. width       : 256,     //设置宽度  
    3. height      : 256,     //设置高度  
    4. typeNumber  : -1,      //计算模式  
    5. correctLevel    : QRErrorCorrectLevel.H,//纠错等级  
    6. background      : "#ffffff",//背景颜色  
    7. foreground      : "#000000" //前景颜色  

    使用方式非常简单

    1. jQuery('#output').qrcode({200,height:200,correctLevel:0,text:content});  

     经过简单实践,

    使用canvas方式渲染性能还是非常不错的,但是如果用table方式,性能不太理想,特别是IE9以下的浏览器,所以需要自行优化一下渲染table的方式,这里就不细述了。

    二、JS生成中文二维码

    其实上面的js有一个小小的缺点,就是默认不支持中文。

    这跟js的机制有关系,jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,

    而这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式,

    英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。

    解决方式当然是,在二维码编码前把字符串转换成UTF-8,具体代码如下:

    1. function utf16to8(str) {  
    2.     var out, i, len, c;  
    3.     out = "";  
    4.     len = str.length;  
    5.     for(i = 0; i < len; i++) {  
    6.     c = str.charCodeAt(i);  
    7.     if ((c >= 0x0001) && (c <= 0x007F)) {  
    8.         out += str.charAt(i);  
    9.     } else if (c > 0x07FF) {  
    10.         out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));  
    11.         out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));  
    12.         out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));  
    13.     } else {  
    14.         out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));  
    15.         out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));  
    16.     }  
    17.     }  
    18.     return out;  
    19. }  

    参考:

    https://github.com/jeromeetienne/jquery-qrcode

    http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

  • 相关阅读:
    平衡二叉树之RB树
    平衡二叉树之AVL树
    实现哈希表
    LeetCode Median of Two Sorted Arrays
    LeetCode Minimum Window Substring
    LeetCode Interleaving String
    LeetCode Regular Expression Matching
    PAT 1087 All Roads Lead to Rome
    PAT 1086 Tree Traversals Again
    LeetCode Longest Palindromic Substring
  • 原文地址:https://www.cnblogs.com/haw2106/p/6646259.html
Copyright © 2011-2022 走看看