使用 JS 写一个验证码,并在前端进行校验
新建文件 VueImageVerify.vue
<template>
<div class="img-verify">
<canvas ref="verify" :width="state.width" :height="state.height" @click="handleDraw"></canvas>
</div>
</template>
<script setup>
import {
reactive, onMounted, ref } from 'vue'
const verify = ref(null)
const state = reactive({
pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // 字符串
width: 120,
height: 40,
imgCode: ''
})
defineExpose({
state })
onMounted(() => {
// 初始化绘制图片验证码
state.imgCode = draw()
})
// 点击图片重新绘制
const handleDraw = () => {
state.imgCode = draw()
}
// 随机数
const randomNum = (min, max) => {
return parseInt(Math.random() * (max - min) + min)
}
// 随机颜色
const randomColor = (min, max) => {
const r = randomNum(min, max)
const g = randomNum(min, max)
const b = randomNum(min, max)
return `rgb(${
r},${
g},${
b})`
}
// 绘制图片
const draw = () => {
// 3.填充背景颜色,背景颜色要浅一点
const ctx = verify.value.getContext('2d')
// 填充颜色
ctx.fillStyle = randomColor(180, 230)
// 填充的位置
ctx.fillRect(0, 0, state.width, state.height)
// 定义paramText
let imgCode = ''
// 4.随机产生字符串,并且随机旋转
for (let i = 0; i < 4