<body> <canvas id="canvas" width="120" height="30" style="cursor: pointer"></canvas> <input type="text" id="code" placeholder="不区分大小写"> <input type="button" value="验证" onclick="clickEvent()"> </body> </html> <script> var numArr = [] var canvas = document.querySelector('#canvas'); var ctx = canvas.getContext('2d'); draw(); canvas.onclick = function () { ctx.clearRect(0, 0, 120, 30); draw(); } function draw() { /*绘制一个矩形 颜色随机*/ ctx.fillStyle = randColor(170, 250); ctx.fillRect(0, 0, 120, 50); var data = 'qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890'; for (var i = 0; i <= 90; i += 30) { var c = data[randNum(0, data.length - 1)]; //index 随机数 ===>>>[0,data.length-1] numArr.push(c) //生成的四个随机数存数组 ctx.fillStyle = randColor(60, 160); ctx.font = randNum(15, 40) + 'px SimHei'; ctx.fillText(c, i + randNum(0, 15), randNum(15, 30)); } /*绘制干扰线*/ for (var i = 0; i < 10; i++) { ctx.beginPath(); ctx.moveTo(randNum(0, 120), randNum(0, 120)); ctx.lineTo(randNum(0, 120), randNum(0, 120)); ctx.strokeStyle = randColor(60, 160); ctx.stroke(); } /*绘制干扰点*/ // for (var i = 0; i < 10; i++) { // ctx.beginPath(); // ctx.arc(randNum(0, 120), randNum(0, 30), randNum(1, 5), 0, 2 * Math.PI); // ctx.strokeStyle = randColor(60, 160); // ctx.stroke() // } } function randColor(min, max) { var r = Math.floor(Math.random() * (max - min + 1) + min); //170+[0,80) var g = Math.floor(Math.random() * (max - min + 1) + min); var b = Math.floor(Math.random() * (max - min + 1) + min); return 'rgb(' + r + ',' + g + ',' + b + ')'; } function randNum(min, max) { var num = Math.floor(Math.random() * (max - min + 1) + min); return num; } function clickEvent() { var codeNum = numArr.join("") //生成的验证码 var inputValue = document.getElementById("code").value //输入的验证码 var reg = /^[a-zA-Z0-9]{4}$/; if (reg.test(inputValue)) { if (inputValue.toLowerCase() == codeNum.toLowerCase()) { alert("验证码成功!"); } else { alert("验证码错误!"); } console.log(inputValue.toLowerCase()) console.log(codeNum.toLowerCase()) } else { alert("验证码格式错误") } } </script>
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。