前端登陆验证随机数字字母

为了辨别是否是机器人登录,现在很多网站都加上了登录校验。校验方式也有很多种,这篇文章是随机数字字母的案例。

直接上代码:

父组件:
<template>
  <div class="code">
    <div class="code-input">
      <input type="text" placeholder="图形验证码" v-model="codes" @keyup.enter="view" />
      <Identify class="numberCode" @transfer="getText"></Identify>
    </div>
  </div>
</template>

<script>
import Identify from '@/components/code/identify.vue'
export default {
  data() {
    return {
      codes: '',
      code: ''
    }
  },
  components: { Identify },
  methods: {
    getText(value) {
      this.code = value
    },
    view() {
      if (this.codes == this.code) {
        alert('输入正确')
      } else {
        alert('请重新输入验证码')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.code {
  height: 100vh;
  background-color: #ffffff;
  .code-input {
    display: flex;
    align-items: center;
    margin: 19px;
    input {
      width: 239x;
      margin-right: 10px;
      height: 45px;
      border: 1px solid #ebebeb;
      border-radius: 5px;
      padding-left: 10px;
    }
    .numberCode {
      height: 45px;
    }
  }
}
</style>
子组件identify.vue

<template>
  <div>
    <canvas ref="canvas" width="100" height="45" @click="refreshCode"></canvas>
  </div>
</template>
 
<script>
export default {
  name: 'identify',
  data() {
    return {
      identifyCode: '',
      totalText: ''
    }
  },
  mounted() {
    this.refreshCode()
  },
  methods: {
    drawPic() {
      // 生成随机的字母数字
      this.identifyCode = Math.random().toString(36).substr(2, 4)
      let canvas = this.$refs.canvas
      //canvas添加样式
      canvas.style.border = '1px solid #ebebeb'
      canvas.style.borderRadius = '5px'
      let ctx = canvas.getContext('2d')
      ctx.textBaseline = 'bottom'
      // 绘制背景
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, 100, 45)
      // 绘制文字
      this.totalText = ''
      for (let i = 0; i < this.identifyCode.length; i++) {
        this.drawText(ctx, this.identifyCode[i], i)
        this.totalText += this.identifyCode[i]
      }
      console.log('totalText', this.totalText)
    },
    drawText(ctx, txt, i) {
      // 生成一个随机的颜色
      ctx.fillStyle = `rgb(${parseInt(Math.random() * 255)}, ${parseInt(Math.random() * 255)}, ${parseInt(Math.random() * 255)})`
      ctx.font = '30px SimHei'
      let x = (i + 1) * 20 - 10
      let y = 35
      // 修改坐标原点
      ctx.translate(x, y)
      ctx.fillText(txt, 0, 0)
      ctx.translate(-x, -y)
    },
    refreshCode() {
      this.drawPic()
      this.$emit('transfer', this.totalText)
    }
  }
}
</script>
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值