Home > Article > Web Front-end > Example of using jquery.qrcode to generate a color QR code_jquery
jquery.qrcode.js is a plug-in for drawing QR codes in the jquery class library. It is used to realize QR code graphics rendering and supports two drawing methods: canvas and table. (When jquery.qrcode.js sets the display mode to table, it will be deformed in webkit core browsers such as chrome. This needs attention.)
The following is the test code (color control has been added, the color values of 4 blocks can be set, and render needs to be specified as table.), the effect is as follows:
The code is as follows:
<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>
The jquery-qrcode library uses the charCodeAt method for encoding conversion, and this method will obtain its Unicode encoding by default. Generally, decoders use UTF-8, ISO-8859-1, etc., in English No problem. If it is Chinese, generally Unicode is implemented in UTF-16, with a length of 2 digits, while UTF-8 encoding is 3 digits, so the encoding and decoding of the QR code will not match.
Solution: Convert the string to UTF-8 before encoding the QR code. The specific code is as follows: utf16to8 function