實現彩色二維碼程式碼實

antzone發表於2017-03-22

二維碼可謂在當前大行其道,是個網站都想搞上一個二維碼,且不說是否有人會使用這個二維碼。

下面就是一段能夠實現彩色二維效果的程式碼例項,希望能夠給需要的朋友帶來幫助。

程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</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 type="text/javascript">
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>

相關文章