首先说一下要求:
1. 绘制一个随机验证码
2. 验证码中有10 个干扰线条 30 个干扰点 验证内容 包含数字以及字母 随机位置 长度为 5
html部分主要包括一个canvas标签以及一个用来刷新的button, css部分基本每内容就不说了。
<canvas width="400" height="300"></canvas>
<button id="newCode">验证码无法识别 点击刷新</button>
js部分我们再来一步步分析。
首先用到一个取随机数的function 和一些声明:
var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
var canvas = document.getElementsByTagName('canvas')[0]
var ctx = canvas.getContext('2d')
var btn = document.getElementById('newCode')
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
然后就是取验证码的function:
function testCode() {
ctx.clearRect(0, 0, 400, 300)
// 加干扰线条
for (var i = 0; i < 10; i++) {
ctx.beginPath()
// 随机宽度
ctx.lineWidth = getRandom(1, 10)
// 随机颜色
ctx.strokeStyle = `rgb(${getRandom(0, 255)}, ${getRandom(0, 255)}, ${getRandom(0, 255)})`
// 随机位置
var x = getRandom(1, 399)
var y = getRandom(1, 299)
ctx.moveTo(x, y)
ctx.lineTo(x + getRandom(10, 100), y + getRandom(10, 100))
ctx.stroke()
ctx.closePath()
}
// 加干扰点
for (var i = 0; i < 29; i++) {
ctx.beginPath()
// 随机颜色
ctx.strokeStyle = `rgb(${getRandom(0, 255)}, ${getRandom(0, 255)}, ${getRandom(0, 255)})`
// 随机位置
var x = getRandom(1, 399)
var y = getRandom(1, 299)
// 绘制随机半径的圆
ctx.arc(x, y, getRandom(1, 20), 0, Math.PI * 2)
ctx.fillStyle = `rgb(${getRandom(0, 255)}, ${getRandom(0, 255)}, ${getRandom(0, 255)})`
ctx.fill()
ctx.closePath()
}
// 加验证码
var x = 20
for (var i = 0; i < 5; i++) {
x += getRandom(20, 70)
ctx.font = `${getRandom(30, 40)}px serif`;
var a = parseInt(getRandom(0, data.length - 1))
ctx.fillStyle = `rgb(${getRandom(0, 255)}, ${getRandom(0, 255)}, ${getRandom(0, 255)})`
ctx.fillText(`${data[a]}`, x, getRandom(30, 270));
}
}
最后 让网页打开时运行一次验证码函数 以及给button绑定上这个函数
testCode()
btn.onclick = function () {
testCode()
}
以上就是取验证码的分析。