vue3+canvas实现数字验证码

<template>
  <canvas
    ref="canvas"
    :width="state.contentWidth"
    :height="state.contentHeight"
    @click="changeCanvasVal"
  ></canvas>
</template>

<script setup>
import { reactive, ref, onMounted, watch } from "vue";

const canvas = ref();

const state = reactive({
  contentWidth: 210,
  contentHeight: 50,
  valicodes: "abcdefghijklmnopqrstuvwxyz1234567890",
  identifyCode: "",
  count: 6, //个数
});
onMounted(() => {
  state.identifyCode = draw();
  console.log(state.identifyCode);
});
watch(
  () => {
    return state.identifyCode;
  },
  (newval, oldval) => {
    console.log(newval);
  }
);
//随机数
const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
};
//随机颜色
const randomColor = (min, max) => {
  let r = randomNum(min, max);
  let g = randomNum(min, max);
  let b = randomNum(min, max);
  return `rgb(${r},${g},${b})`;
};
//干扰线
const drawLine = (ctx) => {
  for (let i = 0; i < 5; i++) {
    //5条线
    ctx.strokeStyle = randomColor(40, 180);
    ctx.beginPath();
    ctx.moveTo(
      randomNum(0, state.contentWidth),
      randomNum(0, state.contentHeight)
    );
    ctx.lineTo(
      randomNum(0, state.contentWidth),
      randomNum(0, state.contentHeight)
    );
    ctx.stroke();
  }
};
//绘制点
const drawDot = (ctx) => {
  for (let i = 0; i < 20; i++) {
    //20个点
    ctx.fillStyle = randomColor(0, 255);
    ctx.beginPath();
    ctx.arc(
      randomNum(0, state.contentWidth),
      randomNum(0, state.contentHeight),
      1,
      0,
      2 * Math.PI
    );
    ctx.fill();
  }
};
//开始绘制
const draw = () => {
  const ctx = canvas.value.getContext("2d");
  //绘制背景
  ctx.fillStyle = randomColor(220, 255);
  ctx.fillRect(0, 0, state.contentWidth, state.contentHeight);
  // 绘制文字
  let identifyCode = "";

  for (let i = 0; i < state.count; i++) {
    //控制字数
    // drawText(ctx, state.identifyCode[i], i);
    const text = state.valicodes[randomNum(0, state.valicodes.length - 1)];
    identifyCode += text;
    // 字体随机的旋转角度
    var deg = randomNum(-10, 10);
    ctx.font = randomNum(18, 40) + "px Arial"; //字体大小
    ctx.fillStyle = randomColor(50, 160); //字体颜色

    ctx.textBaseline = "middle";

    ctx.save();
    //文字依次随机的上下左右
    let x = (state.contentWidth / state.count) * i + 10;
    let y = randomNum(
      -state.contentHeight / state.count,
      state.contentHeight / state.count
    );
    ctx.translate(x, y);
    ctx.rotate((deg * Math.PI) / 180); //文字旋转角度
    ctx.fillText(text, 0, state.contentHeight / 2);
    ctx.restore();
  }
  //绘制线条
  drawLine(ctx);
  //绘制点
  drawDot(ctx);
  return identifyCode;
};
const changeCanvasVal = () => {
  state.identifyCode = draw();
};
</script>

<style lang="scss"></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值