绘制验证码
/*生成画布:
count:干扰线数量,
text:验证码文本(可以前端自己生成,),
fontSize:字体大小,
width:画布宽度px,
height:画布高度px,
*/
const initCanvas = (count, text, fontSize, width, height) => {
let myCanvas = document.querySelector("#myCanvas")
let ctx = myCanvas.getContext('2d')
drawLine(ctx, count, width, height)
drawTxt(ctx, text, fontSize, width, height)
}
/*绘制干扰线:
ctx:画笔
count:干扰线数量
width:画布宽度px,
height:画布高度px,
*/
const drawLine = (ctx, count, width, height) => {
for (let i = 0; i < count; i++) {
ctx.strokeStyle = randomHexColor();//颜色
ctx.beginPath();
ctx.moveTo(
randomNum(0, width), randomNum(0, height)
);
ctx.lineTo(
randomNum(0, width), randomNum(0, height)
);
ctx.stroke()
}
}
/*绘制验证码:
ctx:画笔,
text:验证码文本,
size:字体大小,
width:画布宽度px,
height:画布高度px,
*/
const drawTxt = (ctx, text, size, width, height) => {
let fontLimit = Math.floor((width - size) / text.length) //每一个字体的位置宽度范围
Array.from(text).forEach((char, i, arr) => {
ctx.fillStyle = randomHexColor() //随机生成字体颜色
ctx.font = `${size}px Arial`;
let x1 = fontLimit * i
let x2 = (width - size) - (arr.length - i - 1) * fontLimit
let x = randomNum(x1, x2)
let y = randomNum(size, height)
ctx.fillText(char, x, y);
})
}
// 随机生成验证码(参数:验证码位数)
const randomCode = (count) => {
const txt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'//长度为62
let text = ''
for (let i = 0; i < count; i++) {
text += txt.charAt(randomNum(0, 62))
}
// 可以在此处将生成的验证码存到页面
return text
}
// 随机生成16进制颜色
const randomHexColor = () => {
let color = `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
if (color !== "0xffffff") {
return color
}
}
// 随机生成数字
const randomNum = (min, max) => {
return Math.floor(Math.random() * (max - min) + min)
}
使用时直接调用 initCanvas(count, text, fontSize, width, height)
,传入相关参数即可。