<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="" name="" id="a1" value="" style="width: 80px;height: 30px;" />
<canvas id="code" width="80" height="30" style="border: 1px solid #00F7DE;vertical-align: middle;cursor: pointer;"></canvas>
<div>
<button type="button" id="b1">提交</button>
</div>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
let txtAll = ''
let codeM = function() {
let canvasW = $("#code").width()
let canvasH = $("#code").height()
/**
* 获取任意区间的随机数字
* */
let getNumRandom = function (Num) {
return Math.floor(Math.random()*Num)
}
// var getRandom=function (maxNum) {
// return Math.floor(Math.random()*maxNum);
// }
/**
* 获取随机颜色rgba
* */
let getColorRandom = function () {
let r = getNumRandom(256),
g = getNumRandom(256),
b = getNumRandom(256),
a = getNumRandom(256)
return `rgba(${r}, ${g}, ${b}, ${a})`
}
// 开始绘图
let ctx = $("#code")[0].getContext("2d")
ctx.clearRect(0,0,canvasW,canvasH);
let lineNum = 3, arcNum = 20
// 绘制随机线
for(let i = 0; i<lineNum; i++) {
ctx.beginPath() // 重新开始新路径
ctx.moveTo(getNumRandom(canvasW), getNumRandom(canvasH)) // 起点
ctx.lineTo(getNumRandom(canvasW), getNumRandom(canvasH)) // 到哪
ctx.strokeStyle = getColorRandom() // 设置或返回用于笔触的颜色、渐变或模式
ctx.closePath() // 闭合路径
ctx.stroke() // 绘制已定义的路径
}
// 绘制随机点
for(let i = 0; i<arcNum; i++) {
ctx.beginPath() // 重新开始路径
/**
* context.arc(x,y,r,sAngle,eAngle,counterclockwise);
* x: 圆的中心的 x 坐标
* y: 圆的中心的 y 坐标
* r: 圆的半径
* eAngle: 结束角,以弧度计
* sAngle: 起始角,以弧度计。(弧的圆形的三点钟位置是 0 度)
* counterclockwise: 可选。规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针
* **/
ctx.arc(getNumRandom(canvasW), getNumRandom(canvasH), 1, 0, 2*Math.PI)
ctx.fillStyle = getColorRandom() // 设置或返回用于填充绘画的颜色、渐变或模式
ctx.closePath() //闭合路径
ctx.fill() // 填充当前绘制路径
}
// 绘制随机验证码
let codeText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for(let i = 0; i<4; i++) {
// 随机字母数字
let txt = codeText.split("")[getNumRandom(codeText.length)]
txtAll += txt //拿到随机生成的字母数字,方便后面验证
// 绘制
ctx.beginPath()
ctx.font = "23px 微软雅黑"
ctx.fillStyle = getColorRandom()
/**
* context.fillText(text,x,y,maxWidth);
* text: 规定在画布上输出的文本
* x: 开始绘制文本的 x 坐标位置(相对于画布)
* y: 开始绘制文本的 y 坐标位置(相对于画布)
* */
ctx.fillText(txt, 20*i, 25) // 在画布上绘制“被填充的”文本
ctx.closePath()
}
}
codeM()
$("#code").click(function() {codeM()})
$("#b1").on("click", function() {
if($("#a1").val().toLowerCase() === txtAll.toLowerCase()) { // 判断前将字母大小写转换
alert('验证码输入正确')
} else {
alert('验证码输入不正确')
}
})
</script>
</body>
</html>
canvas绘制验证码,然后验证
最新推荐文章于 2023-10-24 16:26:46 发布