直播平台搭建源码,前端canvas动态验证码实现
// 生成一个随机数
const randomNum = (min: number, max: number) => {
return Math.floor(Math.random() * (max – min) + min)
}
// 生成一个随机的颜色
const randomColor = (min: number, max: number) => {
const r = randomNum(min, max)
const g = randomNum(min, max)
const b = randomNum(min, max)
return rgb( + r + , + g + , + b + )
}
//canvas图片刷新
const initCode = () => {
const len = 4
const codeList: [] = []
const chars: string = ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789
const charsLen: number = chars.length
for (let i = 0; i < len; i++) {
codeList.push(chars.charAt(Math.floor(Math.random() * charsLen)))
}
const identifyCode = codeList.join()
console.log(identifyCode)
form.sureCode = identifyCode
//绘制图片
const canvas: HTMLElement | null | any = document.getElementById(cancasCode)
//画布
const ctx = canvas.getContext(2d)
ctx.textBaseline = bottom
//随机背景色
ctx.fillStyle = randomColor(0, 255)
//绘制矩形的长框(
// x矩形左上角的 x 坐标。
// y矩形左上角的 y 坐标。
// width矩形的宽度,以像素计。
// height矩形的高度,以像素计。
// )
ctx.fillRect(0, 0, 100, 40)
//绘制文字
for (let i = 0; i < identifyCode.length; i++) {
//文字颜色
ctx.fillStyle = randomColor(0, 255)
// 文字大小
ctx.font = randomNum(12, 30) + px SimHei
const x = (i + 1) * (100 / (identifyCode.length + 1))
const y = randomNum(30, 35)
var deg = randomNum(-45, 45)
//修改坐标原点与角度
ctx.translate(x, y)
ctx.rotate(deg * (Math.PI / 180))
ctx.fillText(identifyCode[i], 0, 0)
//恢复坐标原点
ctx.rotate(-deg * (Math.PI / 180))
ctx.translate(-x, -y)
}
}
以上就是 直播平台搭建源码,前端canvas动态验证码实现,更多内容欢迎关注之后的文章
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END