验证码一定是人类史上比较伟大的发明,坑了机器人也坑了自己。
来有兴趣的小伙伴请留言验证码输入答案!!
言归正传,验证码的功能主要是
不被机器轻松破解
人眼很好识别
完整代码: https://github.com/zzzzhaoziyi/react-Vcode
效果预览
主要功能:
- 随机生成4个 大 / 小写英文字母 / 阿拉伯数字
- 随机干扰线防止机器轻松破解
- 点击刷新验证码
- dom 结构优化
第一步随机生成4个 大 / 小写英文字母 / 阿拉伯数字
getRandom(max, min, num) {
const asciiNum = ~~(Math.random()*(max-min+1)+min)
if(!Boolean(num)){
return asciiNum
}
const arr = []
for(let i = 0; i < num; i++){
arr.push(this.getRandom(max, min))
}
return arr
}
首先封装了一个函数,主要功能为生成 1 个或者多个随机数,如果为多个则存放在数组中
~~
为位操作符取整, 类似于Math.floor()
,需慎用,因为不够精准
有了这个函数就可以肆意的搞起来了,首先我们要随机出四个 字母或者数字在 state
初始化的时候。
因为点击刷新的时候需要频繁调用,所以把初始化 state
的封成一个函数
initState(){
return {
data: this.getRandom(109,48,4),
rotate: this.getRandom(75,-75,4),
fz: this.getRandom(8,20,4),
color: [this.getRandom(100,255,3),this.getRandom(100,255,4),this.getRandom(100,255,3),this.getRandom(100,255,3)]
}
}
data
为四个字母,使用的 ascii
表的值,抛去其中一些不使用的符号
rotate
为字母旋转的角度, 为了用户体验,不用旋转 180°
!
fz
为字体大小
color
为字体颜色,rgb
模式
一切处理好了之后代码应该是这样子的
class VCode extends Component {
constructor(props) {
super(props)
this.state = {
...this.initState()
}
}
initState(){
return {
data: this.getRandom(109,48,4),
rotate: this.getRandom(75,-75,4),
fz: this.getRandom(8,20,4),
color: [this.getRandom(100,255,3),this.getRandom(100,255,4),this.getRandom(100,255,3),this.getRandom(100,255,3)]
}
}
getRandom(max, min, num) {
const asciiNum = ~~(Math.random()*(max-min+1)+min)
if(!Boolean(num)){
return asciiNum
}
const arr = []
for(let i = 0; i < num; i++){
arr.push(this.getRandom(max, min))
}
return arr
}
render() {
return ()
}
}
正常情况下应为后台生成验证码。
在没有后台或者自己的一些小 demo 的时候可以前端自己生成。
但是安全性很低,请小伙伴谨慎使用