> 技术文档 > vue - 使用canvas绘制验证码

vue - 使用canvas绘制验证码


封装绘制验证码 verify-code.vue

 
const props = defineProps({ width: { type: Number, default: 120, }, height: { type: Number, default: 40, }, codeLength: { type: Number, default: 5, }, }) const captchaText = ref(\'\') const canvasRef = ref() onMounted(() => { refreshCaptcha() }) const emits = defineEmits([\'getCode\']) const generateRandomText = () => { const chars = \'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\' let result = \'\' for (let i = 0; i { captchaText.value = generateRandomText() drawCaptcha() emits(\'getCode\', captchaText.value) } const drawCaptcha = () => { const canvas = canvasRef.value const ctx = canvas.getContext(\'2d\') // 清除画布 ctx.clearRect(0, 0, canvas.width, canvas.height) // 背景色 ctx.fillStyle = \'#f5f5f5\' ctx.fillRect(0, 0, canvas.width, canvas.height) // 绘制文字 ctx.font = \'20px Arial\' ctx.fillStyle = \'#333\' ctx.textAlign = \'center\' ctx.textBaseline = \'middle\' // 添加干扰线 for (let i = 0; i < 5; i++) { ctx.strokeStyle = getRandomColor() ctx.beginPath() ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height) ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height) ctx.stroke() } // 添加噪点 for (let i = 0; i < 30; i++) { ctx.fillStyle = getRandomColor() ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2) } // 绘制文字(每个字符单独处理以增加变形) for (let i = 0; i { const letters = \'0123456789ABCDEF\' let color = \'#\' for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)] } return color } defineExpose({ code: captchaText, refresh: refreshCaptcha, }) .captcha canvas { cursor: pointer; }

使用

 
登录
import VueVerifyCode from \"@/components/verify-code.vue\";const verifyCodeRef = ref();const input = ref(\"\"); //输入的验证码const verifyCode = ref(\"\"); //当前验证码//获取当前验证码const getCode = (code: string) => { verifyCode.value = code;};const submit = ()=>{ //判断验证码是否相同 全部转换为小写 if (input.value.toLocaleLowerCase() !== verifyCode.value.toLocaleLowerCase()) { alert(\'验证码错误!\') verifyCodeRef.value.refresh() return }}