效果演示

使用说明

我对这个图形验证码做了一个组件的封装,如果你的项目是vue项目就粘贴vue章节的组件代码,是react项目就粘贴react章节的组件代码。组件的使用很简单,只需要传递一个prop,prop是更新验证码的方法,方法需要返回验证码的值。如果要改图形容器的大小直接改组件的状态值就行了。

Vue项目中使用图形验证码

1.创建组件PicAuthCode.vue,粘贴如下代码

<template><div style="margin:10px"><canvas ref="canvas":width="contentWidth" :height="contentHeight"/><span :style="this.textStyle" @click="refresh()">换一张</span></div>
</template>
<script>// 作用:防止暴力登录破解和批量注册export default {name: 'SIdentify',props: {setCode:{type:Function,default:()=>''   //更新验证码的方法,返回验证码即可}},data(){return {identifyCode:'',contentWidth: 100,contentHeight: 35,backgroundColorMin: 180,backgroundColorMax:240,fontSizeMin: 25,fontSizeMax: 30,colorMin: 50,colorMax: 160,lineColorMin:40,lineColorMax: 180,dotColorMin: 0,dotColorMax: 255,textStyle:{fontSize:'12px',color:'gray',marginLeft:'6px',cursor:'pointer',padding:'5px',userSelect:"none"}}},methods: {drawPic() {let canvas = this.$refs.canvaslet ctx = canvas.getContext('2d')ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax) ctx.strokeStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax) ctx.fillRect(0, 0, this.contentWidth, this.contentHeight) ctx.strokeRect(0,0,this.contentWidth, this.contentHeight) for (let i = 0; i < this.identifyCode.length; i++) {this.drawText(ctx, this.identifyCode[i], i)}this.drawLine(ctx)this.drawDot(ctx)},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 + ')'},drawText(ctx, txt, i) {ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei' //字体大小ctx.textBaseline = 'alphabetic' let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))let y = this.randomNum(this.fontSizeMax, this.contentHeight - 12)let deg = this.randomNum(-45, 45)ctx.translate(x, y)ctx.rotate(deg * Math.PI / 180) ctx.fillText(txt, 0, 0)ctx.rotate(-deg * Math.PI / 180)ctx.translate(-x, -y)},drawLine(ctx) {for (let i = 0; i < 8; i++) {ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)ctx.beginPath() ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight)) //设置起点x,yctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight)) //绘制直线 x,y 一条当前位置到x,y点的直线ctx.stroke() }},drawDot(ctx) {for (let i = 0; i < 100; i++) {ctx.fillStyle = this.randomColor(0, 255)ctx.beginPath()ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI)ctx.fill()}},refresh(){const words='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'let code=''for(let i=0;i<4;i++){ code+=words[Math.floor( Math.random()*52)]}this.identifyCode=this.setCode()?this.setCode():code}},mounted() {this.refresh()},watch:{identifyCode(){this.drawPic()}}}</script>

2.在父组件中使用图形验证码组件

<template >
<div>
<PicAuthCode :setCode='setCode' />
</div>
</template><script>
import PicAuthCode from "./components/PicAuthCode.vue"export default {methods: {setCode(){const words='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'let code=''for(let i=0;i<4;i++){ code+=words[Math.floor( Math.random()*52)]}return code           }
},
components:{PicAuthCode,
},}
</script>

react项目中使用图形验证码

1.创建组件PicAuthCode.jsx,粘贴如下代码。是类组件就粘贴类组件,是函数组件就粘贴函数组件。
类组件

import React, { Component } from 'react'export default class PicAuthCode extends Component {static defaultProps={     setCode:()=>""       //更新验证码的方法,返回验证码即可}state={contentWidth: 100,contentHeight: 35,codeLength:4,backgroundColorMin: 180,backgroundColorMax:240,fontSizeMin: 25,fontSizeMax: 30,colorMin: 50,colorMax: 160,lineColorMin:40,lineColorMax: 180,dotColorMin: 0,dotColorMax: 255,textStyle:{fontSize:'12px',color:'gray',marginLeft:'6px',cursor:'pointer',padding:'5px',userSelect:"none"}}drawPic=(code)=>{let canvas = this.canvaslet ctx = canvas.getContext('2d')ctx.fillStyle = this.randomColor(this.state.backgroundColorMin, this.state.backgroundColorMax) ctx.strokeStyle = this.randomColor(this.state.backgroundColorMin, this.state.backgroundColorMax) ctx.fillRect(0, 0, this.state.contentWidth,this.state.contentHeight) ctx.strokeRect(0,0,this.state.contentWidth,this.state.contentHeight) for (let i = 0; i < code.length; i++) {this.drawText(ctx,code[i], i)}this.drawLine(ctx)this.drawDot(ctx)}  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 + ')'}drawText=(ctx, txt, i)=>{ctx.fillStyle = this.randomColor(this.state.colorMin,this.state.colorMax)ctx.font = this.randomNum(this.state.fontSizeMin,this.state.fontSizeMax) + 'px SimHei' ctx.textBaseline = 'alphabetic' let x = (i + 1) * (this.state.contentWidth / (this.state.codeLength + 1))let y = this.randomNum(this.state.fontSizeMax, this.state.contentHeight - 12)let deg = this.randomNum(-45, 45)ctx.translate(x, y)ctx.rotate(deg * Math.PI / 180) ctx.fillText(txt, 0, 0)ctx.rotate(-deg * Math.PI / 180)ctx.translate(-x, -y)}drawLine=(ctx)=>{for (let i = 0; i < 8; i++) {ctx.strokeStyle = this.randomColor(this.state.lineColorMin,this.state.lineColorMax)ctx.beginPath() ctx.moveTo(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight)) //设置起点x,yctx.lineTo(this.randomNum(0,this.state.contentWidth), this.randomNum(0, this.state.contentHeight)) //绘制直线 x,y 一条当前位置到x,y点的直线ctx.stroke() }}drawDot=(ctx)=>{for (let i = 0; i < 100; i++) {ctx.fillStyle = this.randomColor(0, 255)ctx.beginPath()ctx.arc(this.randomNum(0, this.state.contentWidth), this.randomNum(0, this.state.contentHeight), 1, 0, 2 * Math.PI)ctx.fill()}}refresh=()=>{const words='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'let code=''for(let i=0;i<this.state.codeLength;i++){ code+=words[Math.floor( Math.random()*52)]}const fooCode=this.props.setCode()fooCode?this.drawPic(fooCode):this.drawPic(code)}componentDidMount(){this.refresh()}render() {return (<div style={{margin:'10px'}}><canvas ref={(el)=>{this.canvas=el}}width={this.state.contentWidth} height={this.state.contentHeight}/><span style={this.state.textStyle} onClick={this.refresh}>换一张</span></div>)}
}

函数组件

import {useState,useEffect,useRef} from 'react'export default function PicAuthCode(props) {PicAuthCode.defaultProps={     setCode:()=>""    //更新验证码的方法,返回验证码即可}const [config]=useState({contentWidth: 100,contentHeight: 35,backgroundColorMin: 180,backgroundColorMax:240,fontSizeMin: 25,fontSizeMax: 30,colorMin: 50,colorMax: 160,lineColorMin:40,lineColorMax: 180,dotColorMin: 0,dotColorMax: 255,textStyle:{fontSize:'12px',color:'gray',marginLeft:'6px',cursor:'pointer',padding:'5px',userSelect:"none"}})  const [identifyCode,setIdentifyCode]=useState('')const canvasRef=useRef()useEffect(()=>{refresh()},[])useEffect(()=>{identifyCode && drawPic()})PicAuthCode.defaultProps={setCode:()=>""      // 更新验证码的函数}const drawPic=()=>{let canvas = canvasRef.currentlet ctx = canvas.getContext('2d')ctx.fillStyle = randomColor(config.backgroundColorMin,config.backgroundColorMax) ctx.strokeStyle = randomColor(config.backgroundColorMin, config.backgroundColorMax) ctx.fillRect(0, 0, config.contentWidth,config.contentHeight) ctx.strokeRect(0,0,config.contentWidth,config.contentHeight) for (let i = 0; i < identifyCode.length; i++) {drawText(ctx,identifyCode[i], i)}drawLine(ctx)drawDot(ctx)}  const randomNum=(min, max)=>{return Math.floor(Math.random() * (max - min) + min)}const randomColor=(min, max)=>{let r = randomNum(min, max)let g = randomNum(min, max)let b = randomNum(min, max)return 'rgb(' + r + ',' + g + ',' + b + ')'}const drawText=(ctx, txt, i)=>{ctx.fillStyle = randomColor(config.colorMin,config.colorMax)ctx.font = randomNum(config.fontSizeMin,config.fontSizeMax) + 'px SimHei' ctx.textBaseline = 'alphabetic' let x = (i + 1) * (config.contentWidth / (identifyCode.length + 1))let y = randomNum(config.fontSizeMax, config.contentHeight - 12)let deg = randomNum(-45, 45)ctx.translate(x, y)ctx.rotate(deg * Math.PI / 180) ctx.fillText(txt, 0, 0)ctx.rotate(-deg * Math.PI / 180)ctx.translate(-x, -y)}const drawLine=(ctx)=>{for (let i = 0; i < 8; i++) {ctx.strokeStyle = randomColor(config.lineColorMin,config.lineColorMax)ctx.beginPath() ctx.moveTo(randomNum(0, config.contentWidth), randomNum(0, config.contentHeight)) //设置起点x,yctx.lineTo(randomNum(0,config.contentWidth), randomNum(0, config.contentHeight)) //绘制直线 x,y 一条当前位置到x,y点的直线ctx.stroke() }}const drawDot=(ctx)=>{for (let i = 0; i < 100; i++) {ctx.fillStyle = randomColor(0, 255)ctx.beginPath()ctx.arc(randomNum(0, config.contentWidth), randomNum(0, config.contentHeight), 1, 0, 2 * Math.PI)ctx.fill()}}const refresh=()=>{const words='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'let code=''for(let i=0;i<4;i++){ code+=words[Math.floor( Math.random()*52)]}props.setCode?setIdentifyCode(props.setCode()):setIdentifyCode(code) }return (<div style={{margin:'10px'}}><canvas ref={canvasRef}width={config.contentWidth} height={config.contentHeight}/><span style={config.textStyle} onClick={refresh}>换一张</span></div>)
}

2.在父组件中使用图形验证码组件

import React, { Component } from 'react'
import PicAuthCode from './components/PicAuthCode 'export default class App extends Component {setCode=()=>{const words='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'let code=''for(let i=0;i<4;i++){ code+=words[Math.floor( Math.random()*52)]}return code}render() {return (<div><PicAuthCode setCode={setCode} /></div>)}
}

在vue项目或者react项目中实现图形验证码功能相关推荐

  1. 手机直播系统开发中关于iOS获取图形验证码功能

    在手机直播系统开发中关于iOS获取图形验证码功能介绍,首先进入注册页面后请求图形验证码接口获取图形验证码的数字组合,然后加载到相应的页面上,在图形验证码页面我们定义了几个属性,字符串的数量.显示的线条 ...

  2. vue项目和react项目中禁止eslint

    vue项目禁止eslint: react项目禁止eslint: 找到webpack.base.conf.js文件,然后注释掉里面 红色框圈住的内容即可.

  3. 1024电商项目的邮箱验证码与图形验证码功能模块

    项目基于springcloudalibaba,模块功能大致概括就是登录页面的时候先完成图形验证码的校验,输入的数字和字母与图片上的相对应之后,会向对应的邮箱或手机号发送邮箱/短信验证码二次验证.这里展 ...

  4. 如何在vue中使用图形验证码

    首先在component问价夹下创建一个新文件夹并叫identity,并在里面编写组件 <template><div class="s-canvas">&l ...

  5. vue 插件 滑块验证_VUE接入腾讯验证码功能(滑块验证)备忘

    最近在用VUE做个简单的用户系统,登录注册需要验证码,想找个那种拖动的,找geetest居然已经不面向小客户了(或者说只有收费套餐). 腾讯防水墙的验证码免费使用,有2000/小时的免费额度,对于小网 ...

  6. html的表单图形验证码怎么做,django中简单图形验证码实现

    要实现django图形验证码,可以使用简单的captcha 一.安装captcha 在Pycharm的terminal中,使用pip安装第三方库: 执行命令: pip install django-s ...

  7. vue 如何实现点击动态更新图形验证码

    一.vue 点击动态更新图形验证码 在验证码的图片上,绑定点击事件 getCaptcha(),同时使用 ref 指明图形验证码的引用对象,代码如下所示: <section class=" ...

  8. vue添加图形验证码功能

    上图看功能,每点击一次切换验证码!前端判断验证码是否输入,后端判断验证码是否正确! html <el-form-item label="验证码" prop="cod ...

  9. 在微信项目的通讯录页面中增加添加联系人功能

    将FloatingActionButton控件添加到微信项目中的通讯录页面 项目基本结构 关键代码 ##效果展示 项目基本结构 在之前项目的基础上添加了ExpandCollapseAdapter类,用 ...

最新文章

  1. 妹妹生了个女儿,纪念一下
  2. laravel-admin集成ueditor编辑器的图片列表显示问题解决方法
  3. pandas使用dropna函数删除dataframe中所有包含缺失值的数据行(drop rows which contain missing vlaues in dataframe)
  4. java.nio.Buffer flip()方法
  5. P4831-Scarlet loves WenHuaKe【组合数学】
  6. basemap安装_【我是解决安装问题系列_1】Mac python basemap安装
  7. 算法与数据结构 (三) 二叉树的简单应用 二叉查找树,二叉堆排序
  8. spring boot配置ip_Spring Cloud 配置中心高可用搭建
  9. 景观连接度指数怎么算都是0的解决方案
  10. 形参与实参的区别---java基础
  11. camera (14)---智能手机双摄像头原理解析:RGB +Depth
  12. react循环的值为什么要有key_糊盒粘箱为什么要检查表面覆膜电晕值
  13. 特斯拉车顶维权女车主称被恐吓 将公布特斯拉提供的不完整数据
  14. Javascript返回顶部和砸金蛋,跑马灯等游戏代码实现
  15. 可下拉选项可模糊查询的文本输入框
  16. Gitlab分支保护
  17. ACL2021_Lexicon Enhanced Chinese Sequence Labelling Using BERT Adapter
  18. 高德地图初体验demo
  19. Softing pnGate系列网关:将PROFIBUS总线集成到PROFINET网络
  20. adb设置代理与取消代理

热门文章

  1. Degenerate Dimensions(原创)
  2. 从0搭建前端脚手架详解(小白也可以搭建)
  3. 购物车retrofit+ok+rxjava
  4. Netty网络聊天(一) 聊天室实战
  5. 计算机毕业设计SSM感动校园人物投稿网站【附源码数据库】
  6. MFC 加载ICON类型BitMap的方式
  7. ESP32S3 VSCODE openocd JTAG调试设置
  8. 使用FDM(free download manager)要小心损坏笔记本电池
  9. 总结几个对象转数组的方法
  10. java 产生随机数_java产生随机数的几种方式