首页 > 其他分享 >图形验证码uni版

图形验证码uni版

时间:2024-05-22 10:44:13浏览次数:16  
标签:code ctx 验证码 randomNum height uni 图形 options

在uniapp中使用平常vue中的图形验证码,发现有些功能如 getContext() 等方法无法使用,网上借鉴的地址 https://blog.csdn.net/DreamPossible20/article/details/130972735

1、在src/utils目录下新建文件mcaptcha.js

// mcaptcha.js
 
export class Mcaptcha {
  constructor(options) {
    this.options = options;
    this.fontSize = options.height * 3 / 6;
    this.init();
    this.refresh();
  }
  init() {
    this.ctx = uni.createCanvasContext(this.options.el);
    this.ctx.setTextBaseline("middle");
    this.ctx.setFillStyle(this.randomColor(180, 240));

  }
  refresh() {
    var code = '';
    var txtArr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O','P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',0,1,2,3,4,5,6,7,8,9]
    for(var i=0;i<4;i++){
      code += txtArr[this.randomNum(0, txtArr.length)];
    }
    this.options.createCodeImg = code;
    let arr = (code + '').split('');
    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(-30, 30);
      this.ctx.translate(dis, this.options.height*0.5);
      this.ctx.rotate(deg * Math.PI / 180);
      this.ctx.fillText(item, 0, 0);
      this.ctx.rotate(-deg * Math.PI / 180);
      this.ctx.translate(-dis, -this.options.height * 0.5);
    })
    for (var i = 0; i < 4; i++) {
      this.ctx.strokeStyle = this.randomColor(40, 180);  //线条颜色
      // this.ctx.strokeStyle = '#E9F1D9'
      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();
    }
    // 验证码上显示小点 我的ui图不显示,根据各自ui图来选择是否加
    // 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 = code.toLowerCase();
    var v_code = this.options.createCodeImg.toLowerCase();
    console.log(code)
    console.log(v_code.substring(v_code.length - 4))
    if (code == v_code.substring(v_code.length - 4)) {
      return true;
    } else {
      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 + ")";
  }
}

2、在使用图形验证码的页面引入并使用
引入

import { Mcaptcha  } from '@/utils/mcaptcha'

初始化

onReady() {
   this.mcaptcha = new Mcaptcha({
     el: 'canvas',
     width: 80,  
     height: 35,
     createCodeImg: ""
   });
 },

页面展示

<view class="code-canvas" @click="updateImageCode">
  <canvas style="width:220rpx;height:86rpx;" canvas-id="canvas"></canvas>
</view>
<style lang="scss" scoped>
        .code-canvas {
        box-sizing: border-box;
        margin: 2px 0px 0px 2px;
        width: 100%;    
        height: 86rpx;
        background: #E9F1D9;   //验证码的背景色 我的ui图是这个,根据所需自行添加,如果透明,此行代码不要
        }
    </style>

刷新图形验证码

// 刷新验证码
updateImageCode() {
  this.mcaptcha.refresh()
},

校验

// 提交前校验图形验证码
submit() {
  if(!!this.userInfo.graphicVerifyCode) {
    return uni.showToast({icon: 'error', title: '请输入图形验证码' })
  }
  let validate = this.mcaptcha.validate(this.userInfo.graphicVerifyCode)
  if(!validate) {
    return uni.showToast({icon: 'error', title: '图形验证码错误' })
  }
  ...
}

标签:code,ctx,验证码,randomNum,height,uni,图形,options
From: https://www.cnblogs.com/wszzj/p/18205713

相关文章

  • 高德地图安卓sdk,在uniapp中实现,地图上多个坐标点,点击坐标点,显示坐标信息
     <template><viewclass="content"><mapid="map":style="{width:'100%',height:'50vh'}":markers="markers":longitude="longitude":latitude=......
  • Unity设置UI和Render的渲染层级
    通过给UI或物体挂载下面脚本,来设置层级usingUnityEngine;usingSystem.Collections;usingUnityEngine.UI;namespaceCommon{//设置UI和render的层级publicclassUIDepth:MonoBehaviour{publicintorder;publicboolisUI=true;......
  • uniapp-vue3-oadmin手机后台实例|vite5.x+uniapp多端仿ios管理系统
    原创vue3+uniapp+uni-ui跨端仿ios桌面后台OA管理模板Uni-Vue3-WeOS。uniapp-vue3-os一款基于uni-app+vite5.x+pinia等技术开发的仿ios手机桌面OA管理系统。实现了自定义桌面栅格磁贴布局、多分屏滑动管理、自定义桌面小部件、辅助触控悬浮球等功能。支持编译到H5+小程序端+App端......
  • Unity性能优化:什么是内存泄露?
    内存泄漏是优化方面的名词,主要是由于不再使用的资源没有及时清理,来释放内存,造成内存的浪费,造成系统卡顿。 或者说,内存就像花呗,额度就这么多,有借要有还,而且手里有闲钱的时候就记得还,以保证内存的充足,如果占着不用,就会在其他需要使用的时候内存不足,就容易崩溃出现问题。 Unity......
  • uni.chooseImage多个上传
     uni.chooseImage({count:9,//从相册选择sourceType:['album'],success:(res)=>{this.fileList=res.tempFiles//res.t......
  • Unity制作一个定时器Timer
    Timer和TimerManager代码usingSystem.Collections;usingUnityEngine;publicclassTimer:MonoBehaviour{publicdelegatevoidNotifier();publicNotifieronTimer;publicNotifieronTimerReset;publicNotifieronTimerComplete;publicfl......
  • Unity制作一个BroadcastUI 跑马灯文字广播
     usingDG.Tweening;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.UI;usingUtils;//挂在UI上面publicclassBroadcastUI:MonoBehaviour{privateboolinited=false;privateBroadcastManbm;......
  • Unity查找物体和组件的方法
    一、找物体:①GameObject:a).Find(stringname)通过物体的名字查找b).FindWithTag(stringtag);通过标签获取添加该标签的一个物体c).FindObjectOfType();依据组件类型d).FindGameObjectsWithTag(stringtag)通过标签获取所有添加该标签的物体数组返回一个组合 ②Transform......
  • Unity的UnityEngine.EventSystems中的接口
    一、IPointerDownHandler,IPointerUpHandler,IPointerClickHandler,IPointerEnterHandler,IPointerExitHandlerpublicvoidOnPointerClick(PointerEventDataeventData){Debug.Log("OnPointerClick,鼠标点击,在点击之后抬起时响应");}publicvoidOnP......
  • Unity编辑器Scene窗口快捷操作
    1.按住crtl,可以一个一个单位移动、缩放、旋转物体,单位距离在Edit-Snapsetting中设置,设置单位大小2.选中物体,按住alt+鼠标左键,可以环视目标物体3.按住V键,可以将物体的顶点接到其他物体的顶点 如果要设置更改其他在Scene窗口中的操作,可以利用MonoBehaviour下的OnDrawGizmos或......