效果演示

使用说明

我对这个图形验证码做了一个组件的封装,如果你的项目是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. css火狐 hover 图片会重新请求,在“unhovering”之后使CSS Hover状态保持不变
  2. 算法--------数组类---------总结
  3. leetcode算法题--掷骰子模拟★★
  4. UDP分两次接收数据包 MSG_PEEK
  5. nyist---组队赛(三)
  6. Netty堆外内存泄露排查与总结 1
  7. antd-vue中的form表单label标签for导致点击文字触发输入框解决方案
  8. 呼叫压力测试软件,MyComm呼叫中心压力测试解决方案
  9. 通过代码创建obj格式的三维模型
  10. 字符编码-- Unicode(1991年)
  11. C语言输出大写金额,人民币大写输出(C语言)
  12. 基于Nextcloud,挂载Google drive,搭建Aria2+AriaNg,实现在线下载BT磁链/在线观看/全功能文件管理/无限容量云盘
  13. python k线斜率计算_关于数据拟合:找到斜率变化点作为自由参数 – Python
  14. 韩信点兵问题(中国剩余定理)
  15. 国内jQuery CDN
  16. 使用C#在VS窗体应用中调起一个选择框,完成图片替换
  17. stc89c51单片机音乐盒系统设计_基于单片机数字音乐盒的设计与实现(附PCB,电路图,程序)...
  18. 【日记】 使用 zip4j 实现压缩包加密
  19. DEEP AUTOENCODING GAUSSIAN MIXTURE MODEL FOR UNSUPERVISED ANOMALY DETECTION
  20. 法国童话故事《小王子》读后感

热门文章

  1. 手机性能测试——如何用loadrunner11完成手机的性能测试
  2. 搜索技术【广度优先搜索】 - 嵌套广度优先搜索 【POJ No. 1475】 推箱子 Pushing Boxes
  3. 决战燕京城-11 阴兵借道风波
  4. ESP8266与网络调试助手的通信(TCP ServerTCP Client)
  5. 详解iOS 音视频的延时
  6. vue-element-admin完整项目实例
  7. labelImg 使用以及安装过程
  8. Flutter Chip 标签
  9. Terraform部署腾讯tke
  10. “公母老虎”取名大全