vue3 + canvas + vant实现登陆注册页面 验证码的组件封装

420 阅读1分钟

什么是canvas

HTML5<canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成.

<canvas> 标签只是图形容器,您必须使用脚本来绘制图形。

验证码组件封装

模板部分

<template>
    <div class="img-verify">
        <canvas ref="verify" :width="width" :height="height" @click="handleDraw"></canvas>
    </div>
</template>

Js部分

<script>
import { onMounted, reactive, ref, toRefs } from 'vue';

export default {
    setup() {
        const verify = ref(null);
        const state = reactive({
            //一个所有字符组成的字符串
            pool: 'QWERTYUIOPLKJHGFDSAZXCVBNM1234567890',
            //组件宽
            width: 120,
            //组件高
            height: 40,
            //验证码内容
            imgCode: ''
        })
        //初始化验证码内容
        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 = () => {
            const ctx = verify.value.getContext('2d');
            //设置颜色
            ctx.fillStyle = randomColor(180, 230);
            // 设置左上角位置和宽高
            ctx.fillRect(0, 0, state.width, state.height);
            let imgCode = '';
            //循环设置每个字符内容和属性
            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);
                // 绘制文本的样式
                ctx.font = fontSize + 'px Simhei'
                // 基线对齐选项
                ctx.textBaseline = 'top';
                //设置颜色
                ctx.fillStyle = randomColor(80, 150);
                // 保存画布 (canvas) 的所有状态
                ctx.save();
                // translate() 方法重新映射画布上的 (0,0) 位置。
                ctx.translate(30 * i + 15, 15);
                // 旋转当前的绘图
                ctx.rotate((deg * Math.PI) / 180);
                // 在指定的 (x,y) 位置填充指定的文本text
                ctx.fillText(text, -15 + 5, -15);
                // save 和 restore 方法是用来保存和恢复 canvas 状态的,都没有参数。Canvas 的状态就是当前画面应用的所有样式和变形的一个快照。
                ctx.restore();
            }
            //随机画出五条直线
            for (let i = 0; i < 5; i++) {
                // beginPath() 方法开始一条路径,或重置当前的路径
                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();
            }
            //随机生成小圆点
            for (let i = 0; i < 40; i++) {
                ctx.beginPath();
                // arc() 方法创建弧/曲线(用于创建圆或部分圆)。
                ctx.arc(randomNum(0, state.width), randomNum(0, state.height), 1, 0, 2 * Math.PI)
                ctx.closePath();
                ctx.fillStyle = randomColor(150, 200);
                // fill() 方法填充当前的图像
                ctx.fill();
            }
            return imgCode
        }

        return {
            ...toRefs(state),
            verify,
            handleDraw,
        }
    }
}
</script>

验证码组件使用

引入

//引入
import VueImageVerify from '../components/VueImageVerify.vue';

注册

//注册
export default {
    components: {
        VueImageVerify
    }
}

使用

//使用
<van-field center clearable v-model="verify" label="验证码" placeholder="请输入验证码">
    <template #button>
        <VueImageVerify ref="verifyRef"></VueImageVerify>
    </template>
</van-field>

验证输入框内容与验证码内容是否相同

重点是如何从验证码组件中获取验证码内容,在使用组件时,绑定了一个ref

<VueImageVerify ref="verifyRef"></VueImageVerify>
setup(){
    const verifyRef = ref(null);
}

用ref拿到验证码内容

//imgCode在验证码组件中return了
const content = verifyRef.value.imgCode;

效果图

4.png