当前位置: 首页 > article >正文

前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)

图形验证码是网站安全防护的重要组成部分,能有效防止自动化脚本进行恶意操作,如何实现一个简单的运算图形验证码?本文封装了一个简单的js类,可以用于生成简单但安全的图形验证码。它支持自定义验证码样式,包括字体大小、颜色以及干扰线的数量和样式。如下图。

核心js文件如下:

// mcaptcha.js

export class Mcaptcha {
  constructor(options) {
    this.options = options;
    this.fontSize = 24;
    this.init();
    this.refresh();
  }
  init() {
    this.ctx = wx.createCanvasContext(this.options.el);
    this.ctx.setTextBaseline("middle");
    this.ctx.setFillStyle(this.randomColor(180, 240));
  }
  refresh() {
    var code = '';
    var num1 = this.randomNum(0, 9)
    var num2 = this.randomNum(0, 9)
    this.options.createCodeImg = code;
    code = num1 + '+' + num2 + '=?'
    this.options.num1 = num1;
    this.options.num2 = num2;
    let arr = [code]
    if (arr.length === 0) {
      arr = ['e', 'r', 'r', 'o', 'r'];
    };
    let offsetLeft = this.options.width * 0.6 / (arr.length - 1);
    let marginLeft = this.options.width * 0.2;
    arr.forEach((item, index) => {
      this.ctx.setFillStyle(this.randomColor(0, 180));
      let size = this.randomNum(24, this.fontSize);
      this.ctx.setFontSize(size);
      let dis = offsetLeft * index + marginLeft - size * 0.3;
      let deg = this.randomNum(-1, 1);
      this.ctx.translate(dis, this.options.height * 0.45);
      this.ctx.rotate(deg * Math.PI / 180);
      this.ctx.fillText(item, 2, this.randomNum(0,10));
      this.ctx.rotate(-deg * Math.PI / 180);
      this.ctx.translate(-20, -this.options.height * 0.6);
    })
    for (var i = 0; i < 4; i++) {
      this.ctx.strokeStyle = this.randomColor(40, 180);
      this.ctx.beginPath();
      this.ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height));
      this.ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height));
      this.ctx.stroke();
    }
    for (var i = 0; i < this.options.width / 4; i++) {
      this.ctx.fillStyle = this.randomColor(0, 255);
      this.ctx.beginPath();
      this.ctx.arc(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height), 1, 0, 2 * Math.PI);
      this.ctx.fill();
    }
    this.ctx.draw();
  }
  validate(code) {
    var code = Number(code)
    var v_code = this.options.num1 + this.options.num2
    if (code == v_code) {
      return true
    } else {
      this.refresh()
      return false
    }
  }
  randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
  }
  randomColor(min, max) {
    let r = this.randomNum(min, max);
    let g = this.randomNum(min, max);
    let b = this.randomNum(min, max);
    return "rgb(" + r + "," + g + "," + b + ")";
  }
}

使用方法

以微信小程序为例,其他环境适当修改。

  1. 引入Mcaptcha.js
import Mcaptcha from './mcaptcha.js';

     2.初始化Mcaptcha实例

在你的页面的JS文件中,创建一个Mcaptcha实例,并传入相应的配置选项。

Page({
  onLoad: function() {
    new Mcaptcha({
      el: 'captchaCanvas', // canvas的ID
      width: 300, // canvas的宽度
      height: 150 // canvas的高度
    });
  }
});

      3.在WXML中添加Canvas元素

在页面的WXML文件中,添加一个Canvas元素,用于展示验证码。

<canvas canvas-id="captchaCanvas" style="width: 300px; height: 150px;"></canvas>

4.使用Mcaptcha实例生成验证码

调用Mcaptcha实例的refresh方法来生成验证码。

Page({
  // ...
  onShow: function() {
    // 假设mcaptcha是之前创建的Mcaptcha实例
    mcaptcha.refresh();
  }
});

5.验证用户输入

当用户输入验证码并提交时,调用Mcaptcha实例的validate方法进行验证

Page({
  // ...
  checkCaptcha: function(inputCode) {
    // 假设mcaptcha是之前创建的Mcaptcha实例
    if (mcaptcha.validate(inputCode)) {
      wx.showToast({
        title: '验证成功!',
        icon: 'success'
      });
    } else {
      wx.showToast({
        title: '验证失败,请重试。',
        icon: 'none'
      });
    }
  }
});

 Mcaptcha.js的核心方法

  • refresh(): 生成新的验证码,包括随机数字、运算符和干扰元素。
  • validate(code): 验证用户输入的验证码是否正确,返回布尔值。
  • randomNum(min, max): 生成指定范围内的随机数。
  • randomColor(min, max): 生成指定范围内的随机颜色。


http://www.kler.cn/news/306514.html

相关文章:

  • 代码随想录 | Day21 | 二叉树:找树左下角的值路径总和
  • 判断链表的全部n个字符是否中心对称。
  • Dbt基本概念与快速入门
  • office 2021安装教程
  • C - Make Isomorphic题解
  • Java 类和对象-小结(重要)
  • 基于STM32设计的智能货架(华为云IOT)(225)
  • VUE
  • 跨平台集成:在 AI、微服务和 Azure 云之间实现无缝工作流
  • 深入理解算法效率:时间复杂度与空间复杂度
  • Spark_natural_join
  • 828华为云征文 | 华为云Flexusx与Docker技术融合,打造个性化WizNote服务
  • 深入理解中比较两个字符串差异的方法”或“高效比对字符串:diff-match-patch:c++实战指南
  • c++面向对象
  • 栈OJ题——用栈实现队列
  • 嵌入式初学-C语言-数据结构--七
  • 【linux基础】linux中的开发工具(4)--调试器gdb的使用
  • 问题及解决方案汇总
  • 结构体内存对齐
  • 【算法】动态规划—最长公共子序列
  • HTML+CSS - 网页布局之多列布局定位
  • 网络安全应急响应概述
  • 用STM32做一个USB-TTL工具吧
  • JavaScript Promise 异步编程的一些代码分享
  • 远程桌面内网穿透是什么?有什么作用?
  • openssl下载和创建证书
  • 如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
  • C++:opencv多边形逼近二值图轮廓--cv::approxPolyDP
  • Java集合进阶--双列集合
  • R与机器学习系列|15.可解释的机器学习算法(Interpretable Machine Learning)(下)