一.效果图
二、实现
2.1html
<template>
<div class="outer-box">
<div class="code-box">
<div class="inout-code">
<label class="label" for="inputCode">验证码:</label>
<input type="text" v-model="inputCode" id="inputCode" />
</div>
<div class="code-show" @click.prevent="generateCode">
<canvas ref="canvas" width="100" height="40"></canvas>
</div>
</div>
<input type="button" value="确定" @click="checkCode" />
</div>
</template>
2.2js
// 定义响应式变量
const canvas = ref(null);
const code = ref('');
const inputCode = ref('');
// 生成验证码的函数
const generateCode = () => {
const characters = 'qwertyuiopasdfghjklzxcvbnm123456789';
code.value = Array.from({ length: 4 }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
drawCode();
};
// 将验证码绘制到 canvas 上
const drawCode = () => {
const ctx = canvas.value.getContext('2d');
ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
// 绘制背景
ctx.fillStyle = '#9d2e2e';
ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
// 设置字体样式
ctx.font = '24px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// 绘制验证码字符
code.value.split('').forEach((char, index) => {
ctx.fillStyle = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
ctx.fillText(char, (canvas.value.width / 5) * (index + 1), canvas.value.height / 2);
});
};
// 初始化验证码
const initCode = () => {
nextTick(generateCode);
};
// 校验输入的验证码
const checkCode = () => {
if (code.value.toLowerCase() !== inputCode.value.toLowerCase()) {
alert('您输入的验证码不正确');
inputCode.value = '';
generateCode(); // 重新生成验证码
} else {
alert('验证码正确');
}
};
// 组件挂载时生成验证码
onMounted(initCode);
2.3style
<style scoped>
.code-box{
display: flex;
gap: 10px;
align-items: center;
}
</style>