canvas随机数字验证码


<template>
  <canvas ref="canvas" class="canvas" :width="state.contentWidth" :height="state.contentHeight"
    @click="changeCanvasVal"></canvas>
</template>
 
<script setup lang="ts">
import { reactive, ref, onMounted, watch, defineEmits } from "vue";
const canvas = ref();
const state = reactive({
  contentWidth: 80,
  contentHeight: 38,
  valicodes: "1234567890", // 数字
  identifyCode: "",  //储存生成验证码
  count: 4, //个数
});
onMounted(() => {
  state.identifyCode = draw();
});

const emit = defineEmits(['identifyCodeValue', ]) //子组件给父组件传值
watch(() => state.identifyCode, (newVal, oldValue) => {
  emit('identifyCodeValue', newVal)
})

// watch(() => {
//   return state.identifyCode;
// },
//   (newval, oldval) => {
//     console.log(newval, 'newval');
//   }
// );
//随机数
const randomNum = (min: any, max: any) => {
  return Math.floor(Math.random() * (max - min) + min);
};
//开始绘制
const draw = () => {
  const ctx = canvas.value.getContext("2d");
  ctx.rect(30, 30, 20, 20);
  ctx.stroke();
  ctx.fillStyle = '#fff';  //绘制背景
  ctx.lineWidth = 1;  //绘制背景
  ctx.strokeStyle = "blue";
  ctx.beginPath(); // 开始绘制边框
  ctx.fillRect(0, 0, state.contentWidth, state.contentHeight);
  // 绘制文字
  let identifyCode = "";
  for (let i = 0; i < state.count; i++) {
    //控制字数
    const text = state.valicodes[randomNum(0, state.valicodes.length - 1)];
    identifyCode += text;
    ctx.font = 16 + "px Arial"; //字体大小
    ctx.fillStyle = '#606266'; //字体颜色
    ctx.textBaseline = "middle";
    ctx.save();
    //文字依次随机的上下左右
    let x = (state.contentWidth / state.count) * i + 5;
    let y = (2)
    ctx.translate(x, y);
    ctx.fillText(text, 0, state.contentHeight / 2);  //左
    ctx.restore();
  }
  return identifyCode;
};
const changeCanvasVal = () => {
  state.identifyCode = draw();

};

</script>
 
<style lang="scss">
.canvas {
  padding: 0 15px;
  border: 1px solid #d3d3d3;
  border-radius: 5px;
}
</style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值