vue图形验证码组件(vue3&vue2)

3,363 阅读3分钟

vue3封装:

// ts script setup 写法
<template>
    <div class="img-verify">
        <canvas ref="verify" :width="state.width" :height="state.height" @click="handleDraw" />
    </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'

const verify = ref({} as HTMLCanvasElement)
const state = reactive({
    pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // 字符串
    width: 120,
    height: 40,
    imgCode: ''
})
onMounted(() => {
    // 初始化绘制图片验证码
    state.imgCode = draw()
})

// 点击图片重新绘制
const handleDraw = () => {
    state.imgCode = draw()
}

// 随机数
const randomNum = (min: number, max: number) => {
    return parseInt((Math.random() * (max - min) + min + '') as string)
}
// 随机颜色
const randomColor = (min: number, max: number) => {
    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') as any
    // 填充颜色
    ctx.fillStyle = randomColor(180, 230)
    // 填充的位置
    ctx.fillRect(0, 0, state.width, state.height)
    // 定义paramText
    let 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 type="text/css">
.img-verify canvas {
    cursor: pointer;
}
</style>






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

<script type="text/ecmascript-6">
import { reactive, onMounted, ref, toRefs } from 'vue'
export default {
  setup() {
    const verify = ref(null)
    const state = reactive({
      pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // 字符串
      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 = () => {
      // 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; 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
    }

    return {
      ...toRefs(state),
      verify,
      handleDraw
    }
  }
}
</script>
<style type="text/css">
.img-verify canvas {
  cursor: pointer;
}
</style>

vue2-verify

npm i vue2-verify



<template>
      <Verify @success="alert('success')" @error="alert('error')" :type="1"></Verify>
</template>


<script>
    import Verify from 'vue2-verify'

    export default {
        name: 'app',
        methods: {
            alert(text) {
                console.log(text)
            }
        },
        components: {
            Verify
        }
    }
</script>

事件

参数 说明
  • ready 验证码初始化成功的回调函数。
  • success 验证码匹配成功后的回调函数。如要重新初始化:success:function(obj){obj.refresh();}。
  • error 验证码匹配失败后的回调函数。

常规验证码picture

参数 说明
  • type 验证码type为picture或者1
  • width 常规验证码的宽,支持百分比形式设置,如:width:100%。
  • height 常规验证码的高,支持百分比形式设置,如:height:10%。
  • fontSize 常规验证码中的字母&数字的字体大小,默认为30px。
  • codeLength 常规验证码中显示的验证码个数,默认为6。

运算验证码compute

参数 说明
  • type 验证码type为compute或者2
  • figure 运算验证码的位数,默认是100以内的数字,即两位数。如果是要设置三位数,则设置figure:1000。
  • arith 算法选择,支持加、减、乘。设置为1至3分别代表加减乘,0为随机切换。。
  • width 运算验证码的宽,支持百分比形式设置,如:width:100%。
  • height 运算验证码的高,支持百分比形式设置,如:height:10%。
  • fontSize 运算验证码中的数字的字体大小,默认为30px。
  • showButton 是否显示确定按钮,默认为true

滑动验证码slide

参数 说明
  • type 验证码type为slide或者3
  • vOffset 滑动验证码的误差量,如:误差量为5px就能完成验证,设置vOffset:5。
  • explain 滑动条内的提示,不设置默认是:向右滑动完成验证。
  • barSize 其中包含了width、height两个参数,分别代表滑动条的宽度和高度,支持百分比方式设置,如:{width:‘100%’,height:‘40px’}
  • showButton 是否显示确定按钮,默认为true

拼图验证码puzzle

参数 说明
  • type 验证码type为puzzle或者4
  • mode 验证码的显示方式,弹出式pop,固定fixed,默认是:mode : ‘fixed’。
  • vOffset 滑动验证码的误差量,默认单位是px。如:误差量为5px就能完成验证,设置vOffset:5。
  • vSpace 验证码图片和移动条容器的间隔,默认单位是px。如:间隔为5px,设置vSpace:5。
  • explain 滑动条内的提示,不设置默认是:‘向右滑动完成验证’。
  • imgUrl 背景图片的地址,不设置默认是:‘images/’。
  • imgName 验证码背景图的数组集合,默认从images目录中进行读取,如 [‘1.jpg’, ‘2.jpg’]。
  • imgSize 其中包含了width、height两个参数,分别代表图片的宽度和高度,支持百分比方式设置 如:{width:‘100%’,height:‘200px’}。
  • blockSize 其中包含了width、height两个参数,分别代表拼图块的宽度和高度,如:{width:‘40px’,height:‘40px’}。。
  • barSize 其中包含了width、height两个参数,分别代表滑动条的宽度和高度,支持百分比方式设置,如:{width:‘100%’,height:‘40px’}
  • showButton 是否显示确定按钮,默认为true

选字验证码pick

参数 说明
  • type 验证码type为pick或者5
  • mode 验证码的显示方式,弹出式pop,固定fixed,默认是:mode : ‘fixed’。
  • defaultNum 验证码中出现的文字数量,如要默认4个字
  • checkNum 验证码中要求比对的文字数量,如要按序比对2个字
  • vSpace 验证码图片和移动条容器的间隔,默认单位是px。
  • imgUrl 背景图片的地址,不设置默认是:‘images/’。
  • imgName 验证码背景图的数组集合,默认从images目录中进行读取,如 [‘1.jpg’, ‘2.jpg’]。
  • imgSize 其中包含了width、height两个参数,分别代表图片的宽度和高度,支持百分比方式设置 如:{width:‘100%’,height:‘200px’}。
  • barSize 其中包含了width、height两个参数,分别代表滑动条的宽度和高度,支持百分比方式设置,如:{width:‘100%’,height:‘40px’}
  • showButton 是否显示确定按钮,默认为true