canvas验证码 - 随机字母数字
基于canvas制作随机生成数字英文组合验证码效果,点击或刷新会自动重组。输入验证码提交验证效果代码。
1 <div class="verification"> 2 <input type="text" value="" placeholder="请输入验证码(不区分大小写)" id="verInput"> 3 <canvas id="verCanvas" width="80" height="28"></canvas> 4 <button id="verSubmit" onclick="verify()">提交</button> 5 </div> 6 7 <script type="text/javascript" src="makeCode.js"></script> 8 <script type="text/javascript"> 9 var verCanvas = document.getElementById("verCanvas"); 10 var verValue = makeCode(verCanvas); 11 verCanvas.onclick = function(){ 12 verValue = makeCode(verCanvas); 13 }; 14 function verify(){ 15 var value = document.getElementById("verInput").value; 16 if(value.toLowerCase()==verValue){ 17 alert("验证成功") 18 }else{ 19 alert("验证失败") 20 } 21 } 22 </script>
function makeCode(canvas, codeLenght) { codeLenght = codeLenght || 4; //默认4个字符 var valueArr = []; var canvasWidth = canvas.width; var canvasHeight = canvas.height; var context = canvas.getContext("2d"); context.clearRect(0,0,canvasWidth,canvasHeight); //设置所有可能出现的字符 var codeLib = ["A", "B", "C", "E", "F", "G", "H", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "a", "b", "c", "d", "e", "f", "h", "k", "m", "n", "p", "r", "s", "t", "w", "x", "y", "z", "3", "4", "5", "6", "8"]; var codeLibLength = codeLib.length; for (var i = 0; i < codeLenght; i++) { // 获得随机字符 var txt = codeLib[parseInt(Math.random() * codeLibLength)]; valueArr.push(txt.toLowerCase()); //产生-20~20之间的随机弧度 var deg = (Math.random() * 40-20) * Math.PI / 180; //文字在canvas上的坐标位置 var x = (canvasWidth / (codeLenght + 1)) * (i + 0.5); var y = Math.random()*(canvasHeight*1/5)+(canvasHeight*7/10); //字体设置 var fontSize = canvasHeight*3/4; context.font = "bold " + fontSize + "px 微软雅黑"; context.translate(x, y); context.rotate(deg); context.fillStyle = "rgb("+parseInt(Math.random()*200)+","+parseInt(Math.random()*200)+","+parseInt(Math.random()*200)+")"; context.fillText(txt, 0, 0); context.rotate(-deg); context.translate(-x, -y); } //验证码上显示线条 for (var i = 0; i<5; i++) { context.strokeStyle = "rgb("+parseInt(Math.random()*100+155)+","+parseInt(Math.random()*100+155)+","+parseInt(Math.random()*100+155)+")"; context.beginPath(); context.moveTo(Math.random() * canvasWidth, Math.random() * canvasHeight); context.lineTo(Math.random() * canvasWidth, Math.random() * canvasHeight); context.stroke(); } //验证码上显示小点 for (var i = 0; i <= 24; i++) { context.strokeStyle = "rgb("+parseInt(Math.random()*100+155)+","+parseInt(Math.random()*100+155)+","+parseInt(Math.random()*100+155)+")"; context.beginPath(); var x = Math.random() * canvasWidth; var y = Math.random() * canvasHeight; context.moveTo(x, y); context.lineTo(x + 1, y + 1); context.stroke(); } //返回当前验证码的值 return valueArr.join(""); }