文章目录
- 需求
- 分析
需求
使用 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)// 定义paramTextlet imgCode = ''// 4.随机产生字符串,并且随机旋转for (let i = 0; i < 4; i++) {// 随机的四个字const text = state.pool[randomNum(0, state.pool.length)]imgCode += text// 随机的字体大小const fontSize = randomNum(18, 40)// 字体随机的旋转角度const deg = randomNum(-30, 30)/** 绘制文字并让四个文字在不同的位置显示的思路 :* 1、定义字体* 2、定义对齐方式* 3、填充不同的颜色* 4、保存当前的状态(以防止以上的状态受影响)* 5、平移translate()* 6、旋转 rotate()* 7、填充文字* 8、restore出栈* */ctx.font = fontSize + 'px Simhei'ctx.textBaseline = 'top'ctx.fillStyle = randomColor(80, 150)/** save() 方法把当前状态的一份拷贝压入到一个保存图像状态的栈中。* 这就允许您临时地改变图像状态,* 然后,通过调用 restore() 来恢复以前的值。* save是入栈,restore是出栈。* 用来保存Canvas的状态。save之后,可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作。 restore:用来恢复Canvas之前保存的状态。防止save后对Canvas执行的操作对后续的绘制有影响。** */ctx.save()ctx.translate(30 * i + 15, 15)ctx.rotate((deg * Math.PI) / 180)// fillText() 方法在画布上绘制填色的文本。文本的默认颜色是黑色。// 请使用 font 属性来定义字体和字号,并使用 fillStyle 属性以另一种颜色/渐变来渲染文本。// context.fillText(text,x,y,maxWidth);ctx.fillText(text, -15 + 5, -15)ctx.restore()}// 5.随机产生5条干扰线,干扰线的颜色要浅一点for (let i = 0; i < 5; i++) {ctx.beginPath()ctx.moveTo(randomNum(0, state.width), randomNum(0, state.height))ctx.lineTo(randomNum(0, state.width), randomNum(0, state.height))ctx.strokeStyle = randomColor(180, 230)ctx.closePath()ctx.stroke()}// 6.随机产生40个干扰的小点for (let i = 0; i < 40; i++) {ctx.beginPath()ctx.arc(randomNum(0, state.width), randomNum(0, state.height), 1, 0, 2 * Math.PI)ctx.closePath()ctx.fillStyle = randomColor(150, 200)ctx.fill()}return imgCode
}
</script>
<style>
.img-verify canvas {cursor: pointer;
}
</style>
- 文件
Login.vue
中进行引入
<template><div class="login"><s-header :name="type == 'login' ? '登录' : '注册'" :back="'/home'"></s-header><img class="logo" src="https://s.yezgea02.com/1604045825972/newbee-mall-vue3-app-logo.png" alt=""><div v-if="state.type == 'login'" class="login-body login"><van-form @submit="onSubmit"><van-fieldv-model="state.username"name="username"label="用户名"placeholder="用户名":rules="[{ required: true, message: '请填写用户名' }]"/><van-fieldv-model="state.password"type="password"name="password"label="密码"placeholder="密码":rules="[{ required: true, message: '请填写密码' }]"/><van-fieldcenterclearablelabel="验证码"placeholder="输入验证码"v-model="state.verify"><template #button><vue-img-verify ref="verifyRef" /></template></van-field><div style="margin: 16px;"><div class="link-register" @click="toggle('register')">立即注册</div><van-button round block color="#1baeae" native-type="submit">登录</van-button></div></van-form></div><div v-else class="login-body register"><van-form @submit="onSubmit"><van-fieldv-model="state.username1"name="username1"label="用户名"placeholder="用户名":rules="[{ required: true, message: '请填写用户名' }]"/><van-fieldv-model="state.password1"type="password"name="password1"label="密码"placeholder="密码":rules="[{ required: true, message: '请填写密码' }]"/><van-fieldcenterclearablelabel="验证码"placeholder="输入验证码"v-model="state.verify"><template #button><vue-img-verify ref="verifyRef" /></template></van-field><div style="margin: 16px;"><div class="link-login" @click="toggle('login')">已有登录账号</div><van-button round block color="#1baeae" native-type="submit">注册</van-button></div></van-form></div></div>
</template><script setup>
import { reactive, ref } from 'vue'
import sHeader from '@/components/SimpleHeader.vue'
import vueImgVerify from '@/components/VueImageVerify.vue'
import { login, register } from '@/service/user'
import { setLocal } from '@/common/js/utils'
import md5 from 'js-md5'
import { showSuccessToast, showFailToast } from 'vant'
const verifyRef = ref(null)
const state = reactive({username: '',password: '',username1: '',password1: '',type: 'login',imgCode: '',verify: ''
})// 切换登录和注册两种模式
const toggle = (v) => {state.type = vstate.verify = ''
}// 提交登录或注册表单
const onSubmit = async (values) => {state.imgCode = verifyRef.value.state.imgCode || ''if (state.verify.toLowerCase() != state.imgCode.toLowerCase()) {showFailToast('验证码有误')return}if (state.type == 'login') {const { data } = await login({"loginName": values.username,"passwordMd5": md5(values.password)})setLocal('token', data)// 需要刷新页面,否则 axios.js 文件里的 token 不会被重置window.location.href = '/'} else {await register({"loginName": values.username1,"password": values.password1})showSuccessToast('注册成功')state.type = 'login'state.verify = ''}
}
</script><style lang="less">.login {.logo {width: 120px;height: 120px;display: block;margin: 80px auto 20px;}.login-body {padding: 0 20px;}.login {.link-register {font-size: 14px;margin-bottom: 20px;color: #1989fa;display: inline-block;}}.register {.link-login {font-size: 14px;margin-bottom: 20px;color: #1989fa;display: inline-block;}}.verify-bar-area {margin-top: 24px;.verify-left-bar {border-color: #1baeae;}.verify-move-block {background-color: #1baeae;color: #fff;}}.verify {>div {width: 100%;}display: flex;justify-content: center;.cerify-code-panel {margin-top: 16px;}.verify-code {width: 40%!important;float: left!important;}.verify-code-area {float: left!important;width: 54%!important;margin-left: 14px!important;.varify-input-code {width: 90px;height: 38px!important;border: 1px solid #e9e9e9;padding-left: 10px;font-size: 16px;}.verify-change-area {line-height: 44px;}}}}
</style>