VUE3实现验证码(canvas)

432 阅读1分钟

前言

现在越来越多的登录和注册,都需要通过验证验证码。不多说直接上代码(通过canvas实现)

image.png

代码

<template>
  <input type="text" v-model="input" />
  <br/>
  <br/>
  <canvas
    ref="canvas"
    :width="state.width"
    :height="state.height"
    @click="changeCanvasVal"
  />
  <br/>
  <button @click="onClick">确定</button>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from "vue";
let input=ref<string>("")
const canvas = ref();
const state = reactive({
  pool: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", // 验证码的字符集
  width: 210,
  height: 120,
  canvasVal: "", //验证码值
});
watch(
  () => {
    return state.canvasVal;
  },
  (newval, oldval) => {
    console.log(newval);
  }
);
onMounted(() => {
  state.canvasVal = draw();
});

// 点击图片重新绘制
const changeCanvasVal = () => {
  state.canvasVal = draw();
};

// 随机数
const randomNum = (min: number, max: number) => {
  //含最大值,含最小值
  return Math.floor(Math.random() * (max - min + 1) + min);
};
// 随机颜色,0~255
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 = () => {
  const ctx = canvas.value.getContext("2d");
  ctx.fillStyle = randomColor(220, 255);
  ctx.fillRect(0, 0, state.width, state.height);
  let canvasVal = "";
  //4个字符的验证码
  for (let i = 0; i < 4; i++) {
    const text = state.pool[randomNum(0, state.pool.length - 1)];
    canvasVal += text;
    // 随机的字体大小
    const fontSize = randomNum(18, 30);
    // 字体随机的旋转角度
    const deg = randomNum(-10, 10);
    ctx.font = fontSize + "px Arial";
    ctx.textBaseline = "middle";
    // 随机文字颜色
    ctx.fillStyle = randomColor(80, 150);
    ctx.save();
    //文字随机的上下
    ctx.translate(
      (state.width / 4) * i + 10,
      randomNum(-state.height / 4, state.height / 4)
    );
    ctx.rotate((deg * Math.PI) / 180);
    ctx.fillText(text, 0, state.height / 2);
    ctx.restore();
  }
  // 随机产生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(150, 180);
    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.fillStyle = randomColor(150, 200);
    ctx.fill();
  }
  return canvasVal;
};
const onClick=()=>{
  if(input.value==state.canvasVal){
    console.log("验证通过");
    alert("验证通过")
  }else{
    console.log("验证失败");
    alert("验证失败")
  }
  input.value=""
  state.canvasVal = draw();
}
</script>

结语

结束了,了解过canvas的话还是简单的,不了解的话可以去了解一下。