为了辨别是否是机器人登录,现在很多网站都加上了登录校验。校验方式也有很多种,这篇文章是随机数字字母的案例。
直接上代码:
父组件:
<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>