该验证码函数的功能:
- 忽略大小写
- 点击图刷新验证码
- 返回图中验证码值,便于校验验证码
html
<canvas class="verify" style=" width: 120px; height: 40px; " @click="handleDraw" ></canvas>
js
const randomNum = (min, max) => {
return parseInt(Math.random() * (max - min) + min)
}
var sjyzm = []
let yzYZM = ''
const randomColor = (min, max) => {
const r = randomNum(min, max)
const g = randomNum(min, max)
const b = randomNum(min, max)
return `rgb(${r},${g},${b})`
}
let state={
pool:'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz',
width: 120,
height: 40
}
export function verification(dom){
const ctx = dom.getContext('2d')
ctx.fillStyle = "rgb(255,255,255)"
ctx.fillRect(0, 0, 120, 40)
for (let i = 0; i < 4; i++) {
const text = state.pool[randomNum(0, state.pool.length)]
sjyzm[i] = text
const fontSize = randomNum(18, 40)
const deg = randomNum(-30, 30)
ctx.font = fontSize + '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(text, -15 + 5, -15)
ctx.restore()
}
getYZM()
return yzYZM
}
const getYZM = () =>{
let yzYZMs = ''
sjyzm.forEach(function(item){
item = item.toLowerCase()
yzYZMs =yzYZMs+item
})
yzYZM = yzYZMs
}
使用
var code;
onMounted(()=>{
code= verification(document.querySelector('canvas'))
console.log("验证码************",code)
})
const handleDraw = () => {
code= verification(document.querySelector('canvas'))
console.log("验证码************",code)
}