天天看點

HTML5生成二維碼

js檔案 qrcode.js 代碼

/*from tccdn minify at 2014-6-4 14:59:43,file:/cn/c/c/qrcode.js*/
/**
 * @fileoverview
 * - Using the 'QRCode for Javascript library'
 * - Fixed dataset of 'QRCode for Javascript library' for support full-spec.
 * - this library has no dependencies.
 * 
 * @author davidshimjs
 * @see <a href="http://www.d-project.com/" target="_blank" rel="external nofollow"  target="_blank">http://www.d-project.com/</a>
 * @see <a href="http://jeromeetienne.github.com/jquery-qrcode/" target="_blank" rel="external nofollow"  target="_blank">http://jeromeetienne.github.com/jquery-qrcode/</a>
 */
var QRCode;

(function () {
    //---------------------------------------------------------------------
    // QRCode for JavaScript
    //
    // Copyright (c) 2009 Kazuhiko Arase
    //
    // URL: http://www.d-project.com/
    //
    // Licensed under the MIT license:
    //   http://www.opensource.org/licenses/mit-license.php
    //
    // The word "QR Code" is registered trademark of 
    // DENSO WAVE INCORPORATED
    //   http://www.denso-wave.com/qrcode/faqpatent-e.html
    //
    //---------------------------------------------------------------------
    function QR8bitByte(data) {
        this.mode = QRMode.MODE_8BIT_BYTE;
        this.data = data;
        this.parsedData = [];

        // Added to support UTF-8 Characters
        for (var i = , l = this.data.length; i < l; i++) {
            var byteArray = [];
            var code = this.data.charCodeAt(i);

            if (code > ) {
                byteArray[] =  | ((code & ) >>> );
                byteArray[] =  | ((code & ) >>> );
                byteArray[] =  | ((code & ) >>> );
                byteArray[] =  | (code & );
            } else if (code > ) {
                byteArray[] =  | ((code & ) >>> );
                byteArray[] =  | ((code & ) >>> );
                byteArray[] =  | (code & );
            } else if (code > ) {
                byteArray[] =  | ((code & ) >>> );
                byteArray[] =  | (code & );
            } else {
                byteArray[] = code;
            }

            this.parsedData.push(byteArray);
        }

        this.parsedData = Array.prototype.concat.apply([], this.parsedData);

        if (this.parsedData.length != this.data.length) {
            this.parsedData.unshift();
            this.parsedData.unshift();
            this.parsedData.unshift();
        }
    }

    QR8bitByte.prototype = {
        getLength: function (buffer) {
            return this.parsedData.length;
        },
        write: function (buffer) {
            for (var i = , l = this.parsedData.length; i < l; i++) {
                buffer.put(this.parsedData[i], );
            }
        }
    };

    function QRCodeModel(typeNumber, errorCorrectLevel) {
        this.typeNumber = typeNumber;
        this.errorCorrectLevel = errorCorrectLevel;
        this.modules = null;
        this.moduleCount = ;
        this.dataCache = null;
        this.dataList = [];
    }

function QRPolynomial(num, shift) {
    if (num.length == undefined) throw new Error(num.length + "/" + shift);
    var offset = ;
    while (offset < num.length && num[offset] == ) offset++;
    this.num = new Array(num.length - offset + shift);
    for (var i = ; i < num.length - offset; i++) this.num[i] = num[i + offset];
}

function QRRSBlock(totalCount, dataCount) {
    this.totalCount = totalCount, this.dataCount = dataCount;
}

function QRBitBuffer() {
    this.buffer = [], this.length = ;
}

    QRCodeModel.prototype = {
        "addData": function(data) {
            var newData = new QR8bitByte(data);
            this.dataList.push(newData), this.dataCache = null;
        },
        "isDark": function(row, col) {
            if (row <  || this.moduleCount <= row || col <  || this.moduleCount <= col) throw new Error(row + "," + col);
            return this.modules[row][col];
        },
        "getModuleCount": function() {
            return this.moduleCount;
        },
        "make": function() {
            this.makeImpl(!, this.getBestMaskPattern());
        },
        "makeImpl": function(test, maskPattern) {
            this.moduleCount = this.typeNumber *  + , this.modules = new Array(this.moduleCount);
            for (var row = ; row < this.moduleCount; row++) {
                this.modules[row] = new Array(this.moduleCount);
                for (var col = ; col < this.moduleCount; col++) this.modules[row][col] = null;
            }
            this.setupPositionProbePattern(, ),
            this.setupPositionProbePattern(this.moduleCount - , ),
            this.setupPositionProbePattern(, this.moduleCount - ),
            this.setupPositionAdjustPattern(), this.setupTimingPattern(),
            this.setupTypeInfo(test, maskPattern),
            this.typeNumber >=  && this.setupTypeNumber(test),
            this.dataCache == null && (this.dataCache = QRCodeModel.createData(this.typeNumber, this.errorCorrectLevel, this.dataList)), this.mapData(this.dataCache, maskPattern);
        },
        "setupPositionProbePattern": function(row, col) {
            for (var r = -; r <= ; r++) {
                if (row + r <= - || this.moduleCount <= row + r) continue;
                for (var c = -; c <= ; c++) {
                    if (col + c <= - || this.moduleCount <= col + c) continue;
                     <= r && r <=  && (c ==  || c == ) ||  <= c && c <=  && (r ==  || r == ) ||  <= r && r <=  &&  <= c && c <=  ? this.modules[row + r][col + c] = ! : this.modules[row + r][col + c] = !;
                }
            }
        },
        "getBestMaskPattern": function() {
            var minLostPoint = , pattern = ;
            for (var i = ; i < ; i++) {
                this.makeImpl(!, i);
                var lostPoint = QRUtil.getLostPoint(this);
                if (i ==  || minLostPoint > lostPoint) minLostPoint = lostPoint, pattern = i;
            }
            return pattern;
        },
        "createMovieClip": function(target_mc, instance_name, depth) {
            var qr_mc = target_mc.createEmptyMovieClip(instance_name, depth), cs = ;
            this.make();
            for (var row = ; row < this.modules.length; row++) {
                var y = row * cs;
                for (var col = ; col < this.modules[row].length; col++) {
                    var x = col * cs, dark = this.modules[row][col];
                    dark && (qr_mc.beginFill(, ), qr_mc.moveTo(x, y), qr_mc.lineTo(x + cs, y), qr_mc.lineTo(x + cs, y + cs), qr_mc.lineTo(x, y + cs), qr_mc.endFill());
                }
            }
            return qr_mc;
        },
        "setupTimingPattern": function() {
            for (var r = ; r < this.moduleCount - ; r++) {
                if (this.modules[r][] != null) continue;
                this.modules[r][] = r %  == ;
            }
            for (var c = ; c < this.moduleCount - ; c++) {
                if (this.modules[][c] != null) continue;
                this.modules[][c] = c %  == ;
            }
        },
        "setupPositionAdjustPattern": function() {
            var pos = QRUtil.getPatternPosition(this.typeNumber);
            for (var i = ; i < pos.length; i++) for (var j = ; j < pos.length; j++) {
                var row = pos[i], col = pos[j];
                if (this.modules[row][col] != null) continue;
                for (var r = -; r <= ; r++) for (var c = -; c <= ; c++) r == - || r ==  || c == - || c ==  || r ==  && c ==  ? this.modules[row + r][col + c] = ! : this.modules[row + r][col + c] = !;
            }
        },
        "setupTypeNumber": function(test) {
            var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
            for (var i = ; i < ; i++) {
                var mod = !test && (bits >> i & ) == ;
                this.modules[Math.floor(i / )][i %  + this.moduleCount -  - ] = mod;
            }
            for (var i = ; i < ; i++) {
                var mod = !test && (bits >> i & ) == ;
                this.modules[i %  + this.moduleCount -  - ][Math.floor(i / )] = mod;
            }
        },
        "setupTypeInfo": function(test, maskPattern) {
            var data = this.errorCorrectLevel <<  | maskPattern, bits = QRUtil.getBCHTypeInfo(data);
            for (var i = ; i < ; i++) {
                var mod = !test && (bits >> i & ) == ;
                i <  ? this.modules[i][] = mod : i <  ? this.modules[i + ][] = mod : this.modules[this.moduleCount -  + i][] = mod;
            }
            for (var i = ; i < ; i++) {
                var mod = !test && (bits >> i & ) == ;
                i <  ? this.modules[][this.moduleCount - i - ] = mod : i <  ? this.modules[][ - i -  + ] = mod : this.modules[][ - i - ] = mod;
            }
            this.modules[this.moduleCount - ][] = !test;
        },
        "mapData": function(data, maskPattern) {
            var inc = -, row = this.moduleCount - , bitIndex = , byteIndex = ;
            for (var col = this.moduleCount - ; col > ; col -= ) {
                col ==  && col--;
                for (;;) {
                    for (var c = ; c < ; c++) if (this.modules[row][col - c] == null) {
                        var dark = !;
                        byteIndex < data.length && (dark = (data[byteIndex] >>> bitIndex & ) == );
                        var mask = QRUtil.getMask(maskPattern, row, col - c);
                        mask && (dark = !dark), this.modules[row][col - c] = dark, bitIndex--, bitIndex == - && (byteIndex++, bitIndex = );
                    }
                    row += inc;
                    if (row <  || this.moduleCount <= row) {
                        row -= inc, inc = -inc;
                        break;
                    }
                }
            }
        }
    }, QRCodeModel.PAD0 = , QRCodeModel.PAD1 = , QRCodeModel.createData = function(typeNumber, errorCorrectLevel, dataList) {
        var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel), buffer = new QRBitBuffer;
        for (var i = ; i < dataList.length; i++) {
            var data = dataList[i];
            buffer.put(data.mode, ), buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber)), data.write(buffer);
        }
        var totalDataCount = ;
        for (var i = ; i < rsBlocks.length; i++) totalDataCount += rsBlocks[i].dataCount;
        if (buffer.getLengthInBits() > totalDataCount * ) throw new Error("code length overflow. (" + buffer.getLengthInBits() + ">" + totalDataCount *  + ")");
        buffer.getLengthInBits() +  <= totalDataCount *  && buffer.put(, );
        while (buffer.getLengthInBits() %  != ) buffer.putBit(!);
        for (;;) {
            if (buffer.getLengthInBits() >= totalDataCount * ) break;
            buffer.put(QRCodeModel.PAD0, );
            if (buffer.getLengthInBits() >= totalDataCount * ) break;
            buffer.put(QRCodeModel.PAD1, );
        }
        return QRCodeModel.createBytes(buffer, rsBlocks);
    }, QRCodeModel.createBytes = function(buffer, rsBlocks) {
        var offset = , maxDcCount = , maxEcCount = , dcdata = new Array(rsBlocks.length), ecdata = new Array(rsBlocks.length);
        for (var r = ; r < rsBlocks.length; r++) {
            var dcCount = rsBlocks[r].dataCount, ecCount = rsBlocks[r].totalCount - dcCount;
            maxDcCount = Math.max(maxDcCount, dcCount), maxEcCount = Math.max(maxEcCount, ecCount), dcdata[r] = new Array(dcCount);
            for (var i = ; i < dcdata[r].length; i++) dcdata[r][i] =  & buffer.buffer[i + offset];
            offset += dcCount;
            var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount), rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - ), modPoly = rawPoly.mod(rsPoly);
            ecdata[r] = new Array(rsPoly.getLength() - );
            for (var i = ; i < ecdata[r].length; i++) {
                var modIndex = i + modPoly.getLength() - ecdata[r].length;
                ecdata[r][i] = modIndex >=  ? modPoly.get(modIndex) : ;
            }
        }
        var totalCodeCount = ;
        for (var i = ; i < rsBlocks.length; i++) totalCodeCount += rsBlocks[i].totalCount;
        var data = new Array(totalCodeCount), index = ;
        for (var i = ; i < maxDcCount; i++) for (var r = ; r < rsBlocks.length; r++) i < dcdata[r].length && (data[index++] = dcdata[r][i]);
        for (var i = ; i < maxEcCount; i++) for (var r = ; r < rsBlocks.length; r++) i < ecdata[r].length && (data[index++] = ecdata[r][i]);
        return data;
    };

    var QRMode = {
        "MODE_NUMBER": ,
        "MODE_ALPHA_NUM": ,
        "MODE_8BIT_BYTE": ,
        "MODE_KANJI": 
    }, QRErrorCorrectLevel = {
        "L": ,
        "M": ,
        "Q": ,
        "H": 
    }, QRMaskPattern = {
        "PATTERN000": ,
        "PATTERN001": ,
        "PATTERN010": ,
        "PATTERN011": ,
        "PATTERN100": ,
        "PATTERN101": ,
        "PATTERN110": ,
        "PATTERN111": 
    }, QRUtil = {
        "PATTERN_POSITION_TABLE": [ [], [ ,  ], [ ,  ], [ ,  ], [ ,  ], [ ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , , ,  ], [ , , , ,  ], [ , , , ,  ], [ , , , ,  ], [ , , , ,  ], [ , , , ,  ], [ , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , , ,  ], [ , , , , , ,  ], [ , , , , , ,  ], [ , , , , , ,  ], [ , , , , , ,  ], [ , , , , , ,  ] ],
        "G15": ,
        "G18": ,
        "G15_MASK": ,
        "getBCHTypeInfo": function(data) {
            var d = data << ;
            while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= ) d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);
            return (data <<  | d) ^ QRUtil.G15_MASK;
        },
        "getBCHTypeNumber": function(data) {
            var d = data << ;
            while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= ) d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);
            return data <<  | d;
        },
        "getBCHDigit": function(data) {
            var digit = ;
            while (data != ) digit++, data >>>= ;
            return digit;
        },
        "getPatternPosition": function(typeNumber) {
            return QRUtil.PATTERN_POSITION_TABLE[typeNumber - ];
        },
        "getMask": function(maskPattern, i, j) {
            switch (maskPattern) {
              case QRMaskPattern.PATTERN000:
                return (i + j) %  == ;
              case QRMaskPattern.PATTERN001:
                return i %  == ;
              case QRMaskPattern.PATTERN010:
                return j %  == ;
              case QRMaskPattern.PATTERN011:
                return (i + j) %  == ;
              case QRMaskPattern.PATTERN100:
                return (Math.floor(i / ) + Math.floor(j / )) %  == ;
              case QRMaskPattern.PATTERN101:
                return i * j %  + i * j %  == ;
              case QRMaskPattern.PATTERN110:
                return (i * j %  + i * j % ) %  == ;
              case QRMaskPattern.PATTERN111:
                return (i * j %  + (i + j) % ) %  == ;
              default:
                throw new Error("bad maskPattern:" + maskPattern);
            }
        },
        "getErrorCorrectPolynomial": function(errorCorrectLength) {
            var a = new QRPolynomial([  ], );
            for (var i = ; i < errorCorrectLength; i++) a = a.multiply(new QRPolynomial([ , QRMath.gexp(i) ], ));
            return a;
        },
        "getLengthInBits": function(mode, type) {
            if ( <= type && type < ) switch (mode) {
              case QRMode.MODE_NUMBER:
                return ;
              case QRMode.MODE_ALPHA_NUM:
                return ;
              case QRMode.MODE_8BIT_BYTE:
                return ;
              case QRMode.MODE_KANJI:
                return ;
              default:
                throw new Error("mode:" + mode);
            } else if (type < ) switch (mode) {
              case QRMode.MODE_NUMBER:
                return ;
              case QRMode.MODE_ALPHA_NUM:
                return ;
              case QRMode.MODE_8BIT_BYTE:
                return ;
              case QRMode.MODE_KANJI:
                return ;
              default:
                throw new Error("mode:" + mode);
            } else {
                if (!(type < )) throw new Error("type:" + type);
                switch (mode) {
                  case QRMode.MODE_NUMBER:
                    return ;
                  case QRMode.MODE_ALPHA_NUM:
                    return ;
                  case QRMode.MODE_8BIT_BYTE:
                    return ;
                  case QRMode.MODE_KANJI:
                    return ;
                  default:
                    throw new Error("mode:" + mode);
                }
            }
        },
        "getLostPoint": function(qrCode) {
            var moduleCount = qrCode.getModuleCount(), lostPoint = ;
            for (var row = ; row < moduleCount; row++) for (var col = ; col < moduleCount; col++) {
                var sameCount = , dark = qrCode.isDark(row, col);
                for (var r = -; r <= ; r++) {
                    if (row + r <  || moduleCount <= row + r) continue;
                    for (var c = -; c <= ; c++) {
                        if (col + c <  || moduleCount <= col + c) continue;
                        if (r ==  && c == ) continue;
                        dark == qrCode.isDark(row + r, col + c) && sameCount++;
                    }
                }
                sameCount >  && (lostPoint +=  + sameCount - );
            }
            for (var row = ; row < moduleCount - ; row++) for (var col = ; col < moduleCount - ; col++) {
                var count = ;
                qrCode.isDark(row, col) && count++, qrCode.isDark(row + , col) && count++, qrCode.isDark(row, col + ) && count++, qrCode.isDark(row + , col + ) && count++;
                if (count ==  || count == ) lostPoint += ;
            }
            for (var row = ; row < moduleCount; row++) for (var col = ; col < moduleCount - ; col++) qrCode.isDark(row, col) && !qrCode.isDark(row, col + ) && qrCode.isDark(row, col + ) && qrCode.isDark(row, col + ) && qrCode.isDark(row, col + ) && !qrCode.isDark(row, col + ) && qrCode.isDark(row, col + ) && (lostPoint += );
            for (var col = ; col < moduleCount; col++) for (var row = ; row < moduleCount - ; row++) qrCode.isDark(row, col) && !qrCode.isDark(row + , col) && qrCode.isDark(row + , col) && qrCode.isDark(row + , col) && qrCode.isDark(row + , col) && !qrCode.isDark(row + , col) && qrCode.isDark(row + , col) && (lostPoint += );
            var darkCount = ;
            for (var col = ; col < moduleCount; col++) for (var row = ; row < moduleCount; row++) qrCode.isDark(row, col) && darkCount++;
            var ratio = Math.abs( * darkCount / moduleCount / moduleCount - ) / ;
            return lostPoint += ratio * , lostPoint;
        }
    }, QRMath = {
        "glog": function(n) {
            if (n < ) throw new Error("glog(" + n + ")");
            return QRMath.LOG_TABLE[n];
        },
        "gexp": function(n) {
            while (n < ) n += ;
            while (n >= ) n -= ;
            return QRMath.EXP_TABLE[n];
        },
        "EXP_TABLE": new Array(),
        "LOG_TABLE": new Array()
    };

    for (var i = ; i < ; i++) QRMath.EXP_TABLE[i] =  << i;

    for (var i = ; i < ; i++) QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - ] ^ QRMath.EXP_TABLE[i - ] ^ QRMath.EXP_TABLE[i - ] ^ QRMath.EXP_TABLE[i - ];

    for (var i = ; i < ; i++) QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;

    QRPolynomial.prototype = {
        "get": function(index) {
            return this.num[index];
        },
        "getLength": function() {
            return this.num.length;
        },
        "multiply": function(e) {
            var num = new Array(this.getLength() + e.getLength() - );
            for (var i = ; i < this.getLength(); i++) for (var j = ; j < e.getLength(); j++) num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
            return new QRPolynomial(num, );
        },
        "mod": function(e) {
            if (this.getLength() - e.getLength() < ) return this;
            var ratio = QRMath.glog(this.get()) - QRMath.glog(e.get()), num = new Array(this.getLength());
            for (var i = ; i < this.getLength(); i++) num[i] = this.get(i);
            for (var i = ; i < e.getLength(); i++) num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
            return (new QRPolynomial(num, )).mod(e);
        }
    }, QRRSBlock.RS_BLOCK_TABLE = [ [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ], [ , , , , ,  ] ], QRRSBlock.getRSBlocks = function(typeNumber, errorCorrectLevel) {
        var rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel);
        if (rsBlock == undefined) throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel);
        var length = rsBlock.length / , list = [];
        for (var i = ; i < length; i++) {
            var count = rsBlock[i *  + ], totalCount = rsBlock[i *  + ], dataCount = rsBlock[i *  + ];
            for (var j = ; j < count; j++) list.push(new QRRSBlock(totalCount, dataCount));
        }
        return list;
    }, QRRSBlock.getRsBlockTable = function(typeNumber, errorCorrectLevel) {
        switch (errorCorrectLevel) {
          case QRErrorCorrectLevel.L:
            return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - ) *  + ];
          case QRErrorCorrectLevel.M:
            return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - ) *  + ];
          case QRErrorCorrectLevel.Q:
            return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - ) *  + ];
          case QRErrorCorrectLevel.H:
            return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - ) *  + ];
          default:
            return undefined;
        }
    }, QRBitBuffer.prototype = {
        "get": function(index) {
            var bufIndex = Math.floor(index / );
            return (this.buffer[bufIndex] >>>  - index %  & ) == ;
        },
        "put": function(num, length) {
            for (var i = ; i < length; i++) this.putBit((num >>> length - i -  & ) == );
        },
        "getLengthInBits": function() {
            return this.length;
        },
        "putBit": function(bit) {
            var bufIndex = Math.floor(this.length / );
            this.buffer.length <= bufIndex && this.buffer.push(), bit && (this.buffer[bufIndex] |=  >>> this.length % ), this.length++;
        }
    };
    var QRCodeLimitLength=[[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,],[,,,]];

    function _isSupportCanvas() {
        return typeof CanvasRenderingContext2D != "undefined";
    }

    // android 2.x doesn't support Data-URI spec
    function _getAndroid() {
        var android = false;
        var sAgent = navigator.userAgent;

        if (/android/i.test(sAgent)) { // android
            android = true;
            aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i);

            if (aMat && aMat[]) {
                android = parseFloat(aMat[]);
            }
        }

        return android;
    }

    var svgDrawer = (function() {

        var Drawing = function (el, htOption) {
            this._el = el;
            this._htOption = htOption;
        };

        Drawing.prototype.draw = function (oQRCode) {
            var _htOption = this._htOption;
            var _el = this._el;
            var nCount = oQRCode.getModuleCount();
            var nWidth = Math.floor(_htOption.width / nCount);
            var nHeight = Math.floor(_htOption.height / nCount);

            this.clear();

            function makeSVG(tag, attrs) {
                var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
                for (var k in attrs)
                    if (attrs.hasOwnProperty(k)) el.setAttribute(k, attrs[k]);
                return el;
            }

            var svg = makeSVG("svg" , {'viewBox': '0 0 ' + String(nCount) + " " + String(nCount), 'width': '100%', 'height': '100%', 'fill': _htOption.colorLight});
            svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
            _el.appendChild(svg);

            svg.appendChild(makeSVG("rect", {"fill": _htOption.colorDark, "width": "1", "height": "1", "id": "template"}));

            for (var row = ; row < nCount; row++) {
                for (var col = ; col < nCount; col++) {
                    if (oQRCode.isDark(row, col)) {
                        var child = makeSVG("use", {"x": String(row), "y": String(col)});
                        child.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#template")
                        svg.appendChild(child);
                    }
                }
            }
        };
        Drawing.prototype.clear = function () {
            while (this._el.hasChildNodes())
                this._el.removeChild(this._el.lastChild);
        };
        return Drawing;
    })();

    var useSVG = document.documentElement.tagName.toLowerCase() === "svg";

    // Drawing in DOM by using Table tag
    var Drawing = useSVG ? svgDrawer : !_isSupportCanvas() ? (function () {
        var Drawing = function (el, htOption) {
            this._el = el;
            this._htOption = htOption;
        };

        /**
         * Draw the QRCode
         * 
         * @param {QRCode} oQRCode
         */
        Drawing.prototype.draw = function (oQRCode) {
            var _htOption = this._htOption;
            var _el = this._el;
            var nCount = oQRCode.getModuleCount();
            var nWidth = Math.floor(_htOption.width / nCount);
            var nHeight = Math.floor(_htOption.height / nCount);
            var aHTML = ['<table style="border:0;border-collapse:collapse;">'];

            for (var row = ; row < nCount; row++) {
                aHTML.push('<tr>');

                for (var col = ; col < nCount; col++) {
                    aHTML.push('<td style="border:0;border-collapse:collapse;padding:0;margin:0;width:' + nWidth + 'px;height:' + nHeight + 'px;background-color:' + (oQRCode.isDark(row, col) ? _htOption.colorDark : _htOption.colorLight) + ';"></td>');
                }

                aHTML.push('</tr>');
            }

            aHTML.push('</table>');
            _el.innerHTML = aHTML.join('');

            // Fix the margin values as real size.
            var elTable = _el.childNodes[];
            var nLeftMarginTable = (_htOption.width - elTable.offsetWidth) / ;
            var nTopMarginTable = (_htOption.height - elTable.offsetHeight) / ;
            if (nLeftMarginTable >  && nTopMarginTable > ) {
                elTable.style.margin = nTopMarginTable + "px " + nLeftMarginTable + "px";    
            }
        };

        /**
         * Clear the QRCode
         */
        Drawing.prototype.clear = function () {
            this._el.innerHTML = '';
        };

        return Drawing;
    })() : (function () { // Drawing in Canvas
        function _onMakeImage() {
            this._elImage.src = this._elCanvas.toDataURL("image/png");
            this._elImage.style.display = "block";
            this._elCanvas.style.display = "none";            
        }

        // Android 2.1 bug workaround
        // http://code.google.com/p/android/issues/detail?id=5141
        if (this._android && this._android <= ) {
            var factor =  / window.devicePixelRatio;
            var drawImage = CanvasRenderingContext2D.prototype.drawImage; 
            CanvasRenderingContext2D.prototype.drawImage = function (image, sx, sy, sw, sh, dx, dy, dw, dh) {
                if (("nodeName" in image) && /img/i.test(image.nodeName)) {
                    for (var i = arguments.length - ; i >= ; i--) {
                        arguments[i] = arguments[i] * factor;
                    }
                } else if (typeof dw == "undefined") {
                    arguments[] *= factor;
                    arguments[] *= factor;
                    arguments[] *= factor;
                    arguments[] *= factor;
                }

                drawImage.apply(this, arguments); 
            };
        }

        /**
         * Check whether the user's browser supports Data URI or not
         * 
         * @private
         * @param {Function} fSuccess Occurs if it supports Data URI
         * @param {Function} fFail Occurs if it doesn't support Data URI
         */
        function _safeSetDataURI(fSuccess, fFail) {
            var self = this;
            self._fFail = fFail;
            self._fSuccess = fSuccess;

            // Check it just once
            if (self._bSupportDataURI === null) {
                var el = document.createElement("img");
                var fOnError = function() {
                    self._bSupportDataURI = false;

                    if (self._fFail) {
                        _fFail.call(self);
                    }
                };
                var fOnSuccess = function() {
                    self._bSupportDataURI = true;

                    if (self._fSuccess) {
                        self._fSuccess.call(self);
                    }
                };

                el.onabort = fOnError;
                el.onerror = fOnError;
                el.onload = fOnSuccess;
                el.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // the Image contains 1px data.
                return;
            } else if (self._bSupportDataURI === true && self._fSuccess) {
                self._fSuccess.call(self);
            } else if (self._bSupportDataURI === false && self._fFail) {
                self._fFail.call(self);
            }
        };

        /**
         * Drawing QRCode by using canvas
         * 
         * @constructor
         * @param {HTMLElement} el
         * @param {Object} htOption QRCode Options 
         */
        var Drawing = function (el, htOption) {
            this._bIsPainted = false;
            this._android = _getAndroid();

            this._htOption = htOption;
            this._elCanvas = document.createElement("canvas");
            this._elCanvas.width = htOption.width;
            this._elCanvas.height = htOption.height;
            el.appendChild(this._elCanvas);
            this._el = el;
            this._oContext = this._elCanvas.getContext("2d");
            this._bIsPainted = false;
            this._elImage = document.createElement("img");
            this._elImage.alt = "Scan me!";
            this._elImage.style.display = "none";
            this._el.appendChild(this._elImage);
            this._bSupportDataURI = null;
        };

        /**
         * Draw the QRCode
         * 
         * @param {QRCode} oQRCode 
         */
        Drawing.prototype.draw = function (oQRCode) {
            var _elImage = this._elImage;
            var _oContext = this._oContext;
            var _htOption = this._htOption;

            var nCount = oQRCode.getModuleCount();
            var nWidth = _htOption.width / nCount;
            var nHeight = _htOption.height / nCount;
            var nRoundedWidth = Math.round(nWidth);
            var nRoundedHeight = Math.round(nHeight);

            _elImage.style.display = "none";
            this.clear();

            for (var row = ; row < nCount; row++) {
                for (var col = ; col < nCount; col++) {
                    var bIsDark = oQRCode.isDark(row, col);
                    var nLeft = col * nWidth;
                    var nTop = row * nHeight;
                    _oContext.strokeStyle = bIsDark ? _htOption.colorDark : _htOption.colorLight;
                    _oContext.lineWidth = ;
                    _oContext.fillStyle = bIsDark ? _htOption.colorDark : _htOption.colorLight;                    
                    _oContext.fillRect(nLeft, nTop, nWidth, nHeight);

                    // 안티 앨리어싱 방지 처리
                    _oContext.strokeRect(
                        Math.floor(nLeft) + ,
                        Math.floor(nTop) + ,
                        nRoundedWidth,
                        nRoundedHeight
                    );

                    _oContext.strokeRect(
                        Math.ceil(nLeft) - ,
                        Math.ceil(nTop) - ,
                        nRoundedWidth,
                        nRoundedHeight
                    );
                }
            }

            this._bIsPainted = true;
        };

        /**
         * Make the image from Canvas if the browser supports Data URI.
         */
        Drawing.prototype.makeImage = function () {
            if (this._bIsPainted) {
                _safeSetDataURI.call(this, _onMakeImage);
            }
        };

        /**
         * Return whether the QRCode is painted or not
         * 
         * @return {Boolean}
         */
        Drawing.prototype.isPainted = function () {
            return this._bIsPainted;
        };

        /**
         * Clear the QRCode
         */
        Drawing.prototype.clear = function () {
            this._oContext.clearRect(, , this._elCanvas.width, this._elCanvas.height);
            this._bIsPainted = false;
        };

        /**
         * @private
         * @param {Number} nNumber
         */
        Drawing.prototype.round = function (nNumber) {
            if (!nNumber) {
                return nNumber;
            }

            return Math.floor(nNumber * ) / ;
        };

        return Drawing;
    })();

    /**
     * Get the type by string length
     * 
     * @private
     * @param {String} sText
     * @param {Number} nCorrectLevel
     * @return {Number} type
     */
    function _getTypeNumber(sText, nCorrectLevel) {            
        var nType = ;
        var length = _getUTF8Length(sText);

        for (var i = , len = QRCodeLimitLength.length; i <= len; i++) {
            var nLimit = ;

            switch (nCorrectLevel) {
                case QRErrorCorrectLevel.L :
                    nLimit = QRCodeLimitLength[i][];
                    break;
                case QRErrorCorrectLevel.M :
                    nLimit = QRCodeLimitLength[i][];
                    break;
                case QRErrorCorrectLevel.Q :
                    nLimit = QRCodeLimitLength[i][];
                    break;
                case QRErrorCorrectLevel.H :
                    nLimit = QRCodeLimitLength[i][];
                    break;
            }

            if (length <= nLimit) {
                break;
            } else {
                nType++;
            }
        }

        if (nType > QRCodeLimitLength.length) {
            throw new Error("Too long data");
        }

        return nType;
    }

    function _getUTF8Length(sText) {
        var replacedText = encodeURI(sText).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a');
        return replacedText.length + (replacedText.length != sText ?  : );
    }

    /**
     * @class QRCode
     * @constructor
     * @example 
     * new QRCode(document.getElementById("test"), "http://jindo.dev.naver.com/collie");
     *
     * @example
     * var oQRCode = new QRCode("test", {
     *    text : "http://naver.com",
     *    width : 128,
     *    height : 128
     * });
     * 
     * oQRCode.clear(); // Clear the QRCode.
     * oQRCode.makeCode("http://map.naver.com"); // Re-create the QRCode.
     *
     * @param {HTMLElement|String} el target element or 'id' attribute of element.
     * @param {Object|String} vOption
     * @param {String} vOption.text QRCode link data
     * @param {Number} [vOption.width=256]
     * @param {Number} [vOption.height=256]
     * @param {String} [vOption.colorDark="#000000"]
     * @param {String} [vOption.colorLight="#ffffff"]
     * @param {QRCode.CorrectLevel} [vOption.correctLevel=QRCode.CorrectLevel.H] [L|M|Q|H] 
     */
    QRCode = function (el, vOption) {
        this._htOption = {
            width : , 
            height : ,
            typeNumber : ,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRErrorCorrectLevel.H
        };

        if (typeof vOption === 'string') {
            vOption    = {
                text : vOption
            };
        }

        // Overwrites options
        if (vOption) {
            for (var i in vOption) {
                this._htOption[i] = vOption[i];
            }
        }

        if (typeof el == "string") {
            el = document.getElementById(el);
        }

        this._android = _getAndroid();
        this._el = el;
        this._oQRCode = null;
        this._oDrawing = new Drawing(this._el, this._htOption);

        if (this._htOption.text) {
            this.makeCode(this._htOption.text);    
        }
    };

    /**
     * Make the QRCode
     * 
     * @param {String} sText link data
     */
    QRCode.prototype.makeCode = function (sText) {
        this._oQRCode = new QRCodeModel(_getTypeNumber(sText, this._htOption.correctLevel), this._htOption.correctLevel);
        this._oQRCode.addData(sText);
        this._oQRCode.make();
        this._el.title = sText;
        this._oDrawing.draw(this._oQRCode);            
        this.makeImage();
    };

    /**
     * Make the Image from Canvas element
     * - It occurs automatically
     * - Android below 3 doesn't support Data-URI spec.
     * 
     * @private
     */
    QRCode.prototype.makeImage = function () {
        if (typeof this._oDrawing.makeImage == "function" && (!this._android || this._android >= )) {
            this._oDrawing.makeImage();
        }
    };

    /**
     * Clear the QRCode
     */
    QRCode.prototype.clear = function () {
        this._oDrawing.clear();
    };

    /**
     * @name QRCode.CorrectLevel
     */
    QRCode.CorrectLevel = QRErrorCorrectLevel;
})();
           

調用這個JS檔案代碼:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8"/>
    <script src="js/qrcode.js"></script>
    <style>
        #qrcode{
            /*text-align: center;*/
            /*display: table-cell;*/
            /*width: 96px;*/
            /*height: 96px;*/
            /*vertical-align:middle;*/
            /*position: relative;*/
        }
    </style>
</head>
<body>
<div id="qrcode">
</div>

<input type="text" id="getval"/> <button id="send">點選更換驗證碼</button>
<script>
    window.onload =function(){
        var qrcode = new QRCode(document.getElementById("qrcode"), {
            width : ,//設定寬高
            height : 
        });
        qrcode.makeCode("http://www.baidu.com");
        document.getElementById("send").onclick =function(){
            qrcode.makeCode(document.getElementById("getval").value);
        }
    }


</script>
</body>
</html>
           

其中 調用方法:

var qrcode = new QRCode(elem, {
            width : ,//設定寬高
            height : 
        });
        qrcode.makeCode("http://www.baidu.com");
           

繼續閱讀