以下是一个简单的 JavaScript 随机验证码生成器:

<!DOCTYPE html>
<html>
  <head>
    <title>随机验证码生成器</title>
    <meta charset='utf-8'>
  </head>
  <body>
    <canvas id='captchaCanvas'></canvas>
    <button onclick='refreshCaptcha()'>刷新</button>
    <script>
      // 获取画布
      var canvas = document.getElementById('captchaCanvas');
      var ctx = canvas.getContext('2d');

      // 随机生成验证码
      var captcha = '';
      var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      for (var i = 0; i < 5; i++) {
        captcha += possible.charAt(Math.floor(Math.random() * possible.length));
      }

      // 绘制验证码
      ctx.font = 'bold 20px Arial';
      ctx.fillStyle = '#333';
      ctx.fillText(captcha, 10, 25);

      // 刷新验证码
      function refreshCaptcha() {
        captcha = '';
        for (var i = 0; i < 5; i++) {
          captcha += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillText(captcha, 10, 25);
      }
    </script>
  </body>
</html>

运行代码,您将在画布上看到一个随机生成的验证码。每次单击“刷新”按钮时,将生成一个新的随机验证码。

JavaScript 随机验证码生成器:简单易懂的代码实现

原文地址: https://www.cveoy.top/t/topic/l0Az 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录