前端生成验证码
<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>
真诚赞赏,手留余香
赞赏
随机推荐
MySQL 开发规范
原生JS判断页面滚动到底部
ThinkPHP 5 模型 select 返回的对象转换为数组
NodeJs通过async/await处理异步
CentOS 7 编译安装 Nginx,Naxsi Waf 和 PHP 手记
Vuex中的信息,刷新页面后,数据没有了的解决方案
gps纠偏及大陆地图偏移原因
20180114梦奇
jQuery Mobile提交以后空白
Video.js 播放m3u8