极简原生js图形验证码

前天接到需求要在老项目登陆界面加上验证码功能,因为是内部项目且无需短信验证环节,那就直接用原生js写一个简单的图形验证码。

示例:

思路:此处假设验证码为4位随机数值,数值刷新满足两个条件①页面新进/刷新。②点击图片刷新。(实际情况下还要考虑登录出错刷新,此处只做样式不写进去) 实现过程为1.先写一个canvas标签做绘图容器。 → 2.将拿到的值绘制到容器中并写好样式。 → 3.点击刷新重新绘制。

写一个canvas标签当容器

html 复制代码
<canvas
    style="width: 100px;border: 2px solid rgb(60, 137, 209);background-image: url('https://gd-hbimg.huaban.com/aa3c7f23dfdc7b2d317aa4b77bd6c7b8469564d2dfa8b-Btd5c6_fw658webp');"
    id="captchaCanvas"></canvas>

并设置容器宽高背景颜色或图片等样式

写一个数值绘制到canvas的方法

js 复制代码
//text为传递的数值
function generateCaptcha(text, callback) {
      var canvas = document.getElementById('captchaCanvas');
      var ctx = canvas.getContext('2d');
      // 设置字体及大小
      ctx.font = '100px Comic Sans MS';
      // 设置字体颜色
      ctx.fillStyle = 'rgb(' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ')';
      // 调整文字图形位置
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';
      // 调整阴影范围
      ctx.shadowBlur = Math.random() * 20;
      // 调整阴影颜色
      ctx.shadowColor = 'rgb(' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ')';
      // 调整阴影位置(偏移量)
      ctx.shadowOffsetX = Math.random() * 10;
      ctx.shadowOffsetY = Math.random() * 10;
      // 绘制文字图形及其偏移量
      ctx.fillText(text, 25, 35);
      // 绘制文字边框及其偏移量
      ctx.strokeText(text, Math.random() * 35, Math.random() * 45);

      var imgDataUrl = canvas.toDataURL();
      callback(imgDataUrl);

    }

拿到数值调用绘制方法

此处为样式示例,因此数值我用4位随机数表示,实际情况为你从后端取得的值,并依靠这个值在后端判断验证码是否一致。

js 复制代码
// 调用函数生成验证码并显示在页面上  
    generateCaptcha(Math.floor(Math.random() * 9000) + 1000, function (imgDataUrl) { });

监听标签点击实现点击刷新

此处要注意一定要先清空canvas中已绘制图像再渲染新数值,因此直接将清除范围设置较大。

js 复制代码
 // 监听点击更新验证码
    document.getElementById("captchaCanvas").addEventListener("click", function (event) {
      // 清空画布
      document.getElementById("captchaCanvas").getContext("2d").clearRect(0, 0, 9999, 9999);
      // 调用函数生成验证码并显示在页面上  
      generateCaptcha(Math.floor(Math.random() * 9000) + 1000, function (imgDataUrl) { });
    })

最后实现效果:

完整代码演示

html 复制代码
<!DOCTYPE html>
<html>

<head>
  <title>String to Captcha</title>
</head>

<body>
  <canvas
    style="width: 100px;border: 2px solid rgb(60, 137, 209);background-image: url('https://gd-hbimg.huaban.com/aa3c7f23dfdc7b2d317aa4b77bd6c7b8469564d2dfa8b-Btd5c6_fw658webp');"
    id="captchaCanvas"></canvas>


  <script>
    // 监听点击更新验证码
    document.getElementById("captchaCanvas").addEventListener("click", function (event) {
      // 清空画布
      document.getElementById("captchaCanvas").getContext("2d").clearRect(0, 0, 9999, 9999);
      // 调用函数生成验证码并显示在页面上  
      generateCaptcha(Math.floor(Math.random() * 9000) + 1000, function (imgDataUrl) { });
    })

    function generateCaptcha(text, callback) {
      var canvas = document.getElementById('captchaCanvas');
      var ctx = canvas.getContext('2d');
      // 设置字体及大小
      ctx.font = '100px Comic Sans MS';
      // 设置字体颜色
      ctx.fillStyle = 'rgb(' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ')';
      // 调整文字图形位置
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';
      // 调整阴影范围
      ctx.shadowBlur = Math.random() * 20;
      // 调整阴影颜色
      ctx.shadowColor = 'rgb(' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ', ' + Math.floor(Math.random() * 256) + ')';
      // 调整阴影位置(偏移量)
      ctx.shadowOffsetX = Math.random() * 10;
      ctx.shadowOffsetY = Math.random() * 10;
      // 绘制文字图形及其偏移量
      ctx.fillText(text, 25, 35);
      // 绘制文字边框及其偏移量
      ctx.strokeText(text, Math.random() * 35, Math.random() * 45);

      var imgDataUrl = canvas.toDataURL();
      callback(imgDataUrl);

    }

    // 调用函数生成验证码并显示在页面上  
    generateCaptcha(Math.floor(Math.random() * 9000) + 1000, function (imgDataUrl) { });
  </script>
</body>

</html>
相关推荐
铁皮饭盒15 小时前
Next.js 风格路由内置?Bun FileSystemRouter 凭啥这么香
javascript
小林ixn16 小时前
别再背八股了!从 5 个真实场景彻底搞懂 JavaScript 的 this
javascript
东风破_16 小时前
JavaScript 面试常考的字符串算法:从反转字符串到回文判断
前端·javascript
巴勒个啦16 小时前
D3.js 入门实战:用力导向图可视化项目依赖关系
javascript
不好听61317 小时前
JavaScript 的 this 到底指向谁?
javascript·面试
触底反弹17 小时前
🔥 2026 年爆火的 Harness Engineering 到底是什么?从原理到实战一文讲透
javascript·人工智能·程序员
mONESY17 小时前
一文搞定JavaScript不同场景中 this 的指向问题
javascript
用户2986985301417 小时前
在 React 中使用 JavaScript 合并 Excel 文件
前端·javascript·react.js
大流星17 小时前
LangChainJs之基础模型(一)
javascript·langchain
橘子星17 小时前
JavaScript this 指向全解实战指南
前端·javascript