利用canvas實現的驗證碼效果程式碼例項

admin發表於2017-02-13
本章節分享一段程式碼例項,它利用canvas實現了驗證碼效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#container {
  width: 960px;
  margin: 0 auto;
}
#box1 {
  left: 500px;
  position: absolute;
  top: 300px;
  background: #177889;
  padding: 2px;
}
#box {
  position: relative;
  top: 260px;
  left: 400px;
  display: none;
}
#canvas {
  box-shadow: 10px 10px 10px #ccc;
  background: #f60;
}
#itext {
  height: 20px;
  width: 180px;
}
label {
  font-size: 20px;
  vertical-align: middle;
  padding-right: 5px;
}
#btn {
  height: 30px;
}
</style>
</head>
<body>
<div id="container">
  <div id="box">
    <canvas id="canvas" width="100" height="30"></canvas>
  </div>
  <div id="box1">
    <form>
      <label for="itext">驗證碼:</label>
      <input id="itext" type="text" placeholder="雙擊切換驗證碼">
      <button id="btn">確定</button>
    </form>
  </div>
</div>
<script>
 var ctx = document.getElementById("canvas").getContext("2d");
 loading();
 
 function loading() {
   ctx.fillStyle = "#f60";
   ctx.fillRect(0, 0, 100, 30);
   var box = document.getElementById("box");
   var posx = [20, 40, 60, 80];
   var posy = [13, 18, 15, 20];
   var color = [];
   num = [];
   ctx.font = "20px Arial";
   ctx.textAlign = "center";
   ctx.textBaseline = "middle";
   c(color, num);
   for (var k = 0; k < 4; k++) {
     //   ctx.beginPath();
     ctx.fillStyle = color[k];
     ctx.fillText(num[k], posx[k], posy[k]);
     // ctx.close();
   }
   event();
 }
 
 function event() {
   var input = document.getElementById("itext");
   var btn = document.getElementById("btn");
   input.onmouseover = function() {
     box.style.display = "block";
   };
 
   input.onmouseout = function() {
     box.style.display = "none";
     //  loading();
   };
   input.ondblclick = loading;
   btn.onclick = check;
 }
 
 function c(color, num) {
   for (var j = 0; j < 4; j++) {
     var r, g, b;
     r = Math.floor(Math.random() * 255);
     g = Math.floor(Math.random() * 255);
     b = Math.floor(Math.random() * 255);
     color[j] = "rgb(" + r + "," + g + "," + b + ")";
     num[j] = Math.floor(Math.random() * 9);
   }
 }
 
 function check() {
   var s = '';
   for (var i = 0; i < num.length; i++) {
     s += num<i>;
   }
   var value = document.getElementById("itext").value;
   if (s == value) {
     alert("驗證成功");
   } else {
     alert("驗證碼錯誤");
   }
 }
</script>
</body>
</html></i>

相關文章