前端生成验证码
<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>
真诚赞赏,手留余香
赞赏
随机推荐
DOM、DOM0、DOM1、DOM2和DOM3的关系
Git 重写历史,修改commit 的注释
nginx 代理
理解 e.clientX,e.clientY e.pageX e.pageY e.offsetX e.offsetY
cropper.js 剪切图片并上传的两种方式
jQuery Mobile 换行
发送header文件头信息实现文件下载
vue-router 切换页面时设置过渡动画
MySQL中UNION和UNION ALL的使用
npm err Cannot read property '0' of undefined