原生js配合canvas实现验证码的生成与验证
代码语言:javascript
复制<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#main{
display: flex;
}
#input{
width: 120px;
height: 40px;
margin-left: 30px;
}
</style>
</head>
<body>
<div id="main">
<canvas id="canvas" width="120" height="40"></canvas>
<a href="" onclick="reload()">看不清换一张</a>
<input type="text" name="" id="input" value=""/>
<button type="button" onclick="validation()">验证</button>
</div>
<script type="text/jscript">
function yzmFun(selector,w,h){
// 随机数的生成
function randomNum(min,max){
return parseInt(Math.random()*(max-min) min)
}
//随机生成颜色的函数
function randomColor(min,max) {
let r = randomNum(min,max)
let g = randomNum(min,max)
let b = randomNum(min,max)
return `rgb(${r},${g},${b})`
}
// let w = w
// let h = h
let canvas = document.querySelector(selector)
let ctx = canvas.getContext('2d')
//在canvas绘制背景颜色
ctx.fillStyle = randomColor(180,230)
ctx.fillRect(0,0,w,h)
//随机字符串
let pool = 'ABCDEFGHIGKLIMNOPQRSTUVWXYZabcdefghigklimnopqrstuvwxyz1234567890'
let yzm = ''
//生成随机的验证码
for(let i = 0;i<4;i ){
let c = pool[randomNum(0,pool.length)]
//随机出字体大小
let fs = randomNum(18,40)
//随机字体角度
let deg = randomNum(-30,30)
ctx.font = fs 'px Simhei'
ctx.textBaseline = 'top'
//设置字体颜色
ctx.fillStyle = randomColor(80,150)
//保存
ctx.save()
//位置
ctx.translate(30*i 15,15)
//旋转
ctx.rotate(deg*Math.PI/180)
ctx.fillText(c,-10,-10)
ctx.restore()
yzm =c
}
//随机生成干扰线
for(let i = 0;i<5;i ){
ctx.beginPath()
ctx.moveTo(randomNum(0,w),randomNum(0,h))
ctx.lineTo(randomNum(0,w),randomNum(0,h))
ctx.strokeStyle = randomColor(180,230)
ctx.closePath()
ctx.stroke()
}
//随机产生干扰圆点
for(let i = 0;i<40;i ){
ctx.beginPath()
ctx.arc(randomNum(0,w),randomNum(0,h),1,0,2*Math.PI)
ctx.fillStyle = randomColor(150,200)
ctx.fill()
}
return yzm
}
//调用生成验证码
let yzmStr = yzmFun('#canvas',120,40).toLowerCase()
//验证验证码是否正确
function validation(){
//获取input的值转换为小写
let yzmInput = document.getElementById('input').value.toLowerCase()
if(yzmStr === yzmInput){
window.location.href="success.html"
alert("成功")
}else{
alert("验证码错误")
location.reload()
}
}
//更换验证码
function reload(){
location.reload()
}
console.log(yzmStr)
</script>
</body>
</html>