使用jquery.qrcode生成彩色二維碼實例
jquery.qrcode.js 是居于jquery類庫的繪制二維碼的插件,用它來實現(xiàn)二維碼圖形渲染支持canvas和table兩種繪圖方式。(jquery.qrcode.js 設(shè)置顯示方式為table時在webkit核心瀏覽器如chrome下會變形,這個需要注意。)
下面為測試代碼(增加了顏色控制,可以設(shè)置4個區(qū)塊的顏色值,需要指定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", //設(shè)置渲染方式 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這個方式進行編碼轉(zhuǎn)換的,而這個方法默認會獲取它的 Unicode 編碼,一般的解碼器都是采用UTF-8, ISO-8859-1等方式,英文是沒有問題,如果是中文,一般情況下Unicode是UTF-16實現(xiàn),長度2位,而UTF-8編碼是3位,這樣二維碼的編解碼就不匹配了。
解決方式:在二維碼編碼前把字符串轉(zhuǎn)換成UTF-8,具體代碼如上utf16to8函數(shù)
PS:本站還提供了一個功能非常強大的二維碼生成工具,感興趣的朋友可以參考一下:
相關(guān)文章
jQuery Easyui加載表格出錯時在表格中間顯示自定義的提示內(nèi)容
這篇文章主要介紹了jQuery Easyui加載表格出錯時在表格中間顯示自定義的提示內(nèi)容的相關(guān)資料,需要的朋友可以參考下2016-12-12淺談$(document)和$(window)的區(qū)別
本人在做項目的時候遇到$(document),$(window)這兩種寫法立馬讓我蒙圈了,那么他們的區(qū)別是什么呢,在網(wǎng)友的幫助下,徹底了解了他們的區(qū)別,這里分享給大家。2015-07-07jQuery中ajax請求后臺返回json數(shù)據(jù)并渲染HTML的方法
今天小編就為大家分享一篇jQuery中ajax請求后臺返回json數(shù)據(jù)并渲染HTML的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08jQuery實現(xiàn)點擊后標記當前菜單位置(背景高亮菜單)效果
這篇文章主要介紹了jQuery實現(xiàn)點擊后標記當前菜單位置(背景高亮菜單)效果,涉及jquery鼠標點擊事件及鏈式操作控制元素樣式動態(tài)變換的技巧,需要的朋友可以參考下2015-08-08jquery控制頁面的展開和隱藏實現(xiàn)方法(推薦)
下面小編就為大家?guī)硪黄猨query控制頁面的展開和隱藏實現(xiàn)方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10