当前位置:首页 > JavaScript

js实现验证码

2026-01-08 12:26:39JavaScript

实现验证码的JavaScript方法

生成随机验证码

使用Math.random()生成随机字符串,结合数字和字母:

function generateCaptcha() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captcha = '';
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    captcha += chars[randomIndex];
  }
  return captcha;
}

绘制图形验证码

使用Canvas绘制带干扰元素的验证码:

function drawCaptcha(canvasId, captchaText) {
  const canvas = document.getElementById(canvasId);
  const ctx = canvas.getContext('2d');

  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 填充背景色
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制验证码文本
  ctx.font = '30px Arial';
  ctx.fillStyle = '#333';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  // 添加文本扭曲效果
  for (let i = 0; i < captchaText.length; i++) {
    ctx.save();
    ctx.translate(30 + i * 30, 25);
    ctx.rotate((Math.random() - 0.5) * 0.4);
    ctx.fillText(captchaText[i], 0, 0);
    ctx.restore();
  }

  // 添加干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 添加干扰点
  for (let i = 0; i < 100; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
    ctx.beginPath();
    ctx.arc(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      Math.random() * 2,
      0,
      2 * Math.PI
    );
    ctx.fill();
  }
}

验证用户输入

比较用户输入与生成的验证码:

function validateCaptcha(inputId, storedCaptcha) {
  const userInput = document.getElementById(inputId).value;
  return userInput.toUpperCase() === storedCaptcha.toUpperCase();
}

完整示例实现

HTML结构:

<canvas id="captchaCanvas" width="200" height="50"></canvas>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button onclick="refreshCaptcha()">刷新</button>
<button onclick="checkCaptcha()">验证</button>

JavaScript逻辑:

let currentCaptcha = '';

function initCaptcha() {
  currentCaptcha = generateCaptcha();
  drawCaptcha('captchaCanvas', currentCaptcha);
}

function refreshCaptcha() {
  currentCaptcha = generateCaptcha();
  drawCaptcha('captchaCanvas', currentCaptcha);
}

function checkCaptcha() {
  const isValid = validateCaptcha('captchaInput', currentCaptcha);
  alert(isValid ? '验证通过' : '验证码错误');
  if (!isValid) refreshCaptcha();
}

// 初始化
window.onload = initCaptcha;

安全增强措施

添加点击刷新功能,防止暴力破解:

document.getElementById('captchaCanvas').addEventListener('click', refreshCaptcha);

设置验证码有效期(5分钟):

js实现验证码

let captchaExpireTime;

function generateCaptchaWithExpiry() {
  currentCaptcha = generateCaptcha();
  captchaExpireTime = Date.now() + 300000; // 5分钟
  drawCaptcha('captchaCanvas', currentCaptcha);
}

function validateCaptchaWithExpiry(inputId) {
  if (Date.now() > captchaExpireTime) {
    alert('验证码已过期');
    return false;
  }
  return validateCaptcha(inputId, currentCaptcha);
}

标签: 验证码js
分享给朋友:

相关文章

验证码实现vue

验证码实现vue

验证码实现(Vue) 在Vue中实现验证码功能通常需要结合前端生成和验证逻辑,以及可能的后端校验。以下是两种常见实现方式: 基于Canvas的图形验证码 通过Canvas动态生成包含随机字符的图形验…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

uniapp图形验证码

uniapp图形验证码

uniapp 图形验证码实现方法 在 uniapp 中实现图形验证码功能可以通过多种方式完成,以下是几种常见的实现方案: 使用第三方验证码服务 接入第三方验证码服务如极验、腾讯云验证码等,这些服务通…

js实现交换

js实现交换

交换变量的方法 在JavaScript中,交换两个变量的值有多种方法。以下是常见的几种实现方式: 使用临时变量 通过引入一个临时变量来存储其中一个变量的值,实现交换: let a = 1; le…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…