当前位置:首页 > 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();
  }
}

验证用户输入

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

js实现验证码

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逻辑:

js实现验证码

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分钟):

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
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 //…

js实现

js实现

JavaScript 实现方法 JavaScript 是一种广泛使用的编程语言,适用于网页开发、服务器端编程以及移动应用开发。以下是几种常见的 JavaScript 实现方法: 网页交互功能 使用…

js实现分页

js实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue…