前言
?前面的文章寫過使用Canvas如何實現滑動驗證功能、隨機字符串驗證功能等,今天我們看看如何實現一個計算驗證碼。
?之前的文章有寫過Canvas系列小功能文章,有興趣的可以瞧上一瞧~
?Canvas系列-下雪特效
?Canvas系列-簽字功能
?Canvas系列-滑動驗證
?Canvas系列-字符驗證
實現隨機字符串驗證功能
?效果圖如下,源碼鏈接
canvas計算驗證演示.gif
基本思路
1、根據傳入的range范圍生成兩個隨機數字,并記錄下來
2、然后隨機拿到一個運算符和數字一起拼接成表達式,類似【12+22=?】
3、在canvas畫布中繪制隨機生成的字符,然后繪制干擾線條和圓點
4、根據規則驗證輸入的答案和生成的表達式結果比較
具體實現代碼
// HTML
<div id="app" v-cloak>
<div class="verify-character" :style="{width: `${width}px`}">
<canvas class="canvas_character"
ref="canvas_character"
:width="width"
:height="height"
@click="reset">
</canvas>
<div class="verfify-input">
<input class="input" type="text" v-model="inputValue">
<button @click="reset">重新加載</button>
</div>
</div>
<br>
<button :class="['confirm', state]" @click="verify">
{{ {active:'驗證', success:'驗證通過', fail:'驗證失敗'}[state] }}
</button>
</div>
// JS
const App = {
props: {
width: {
type: Number,
default: 320
},
height: {
type: Number,
default: 60
},
range: {
type: Number,
default: 100
},
operator: {
type: Array,
default: ['+', '-']
}
},
data() {
return {
num1: 0,
num2: 0,
symbol: '+',
result: 0, // 計算結果
inputValue: '',
state: 'active', // 驗證 成功 失敗
}
},
mounted () {
this.init()
},
methods: {
init () {
this.$nextTick(() => {
this.ctx = this.$refs['canvas_character'].getContext('2d');
this.drawFormula();
})
},
// 繪制圖形碼
drawFormula () {
this.ctx.fillStyle = this.randomColor(180, 240);
this.ctx.fillRect(0, 0, this.width, this.height);
// 繪制干擾線
for (let j = 0; j < 3; j++) {
this.ctx.strokeStyle = this.randomColor(40, 180)
this.ctx.beginPath()
this.ctx.moveTo(this.randomNum(0, this.width), this.randomNum(0, this.height))
this.ctx.lineTo(this.randomNum(0, this.width), this.randomNum(0, this.height))
this.ctx.stroke()
}
// 繪制干擾點
for (let k = 0; k < 30; k++) {
this.ctx.fillStyle = this.randomColor(0, 255)
this.ctx.beginPath()
this.ctx.arc(this.randomNum(0, this.width), this.randomNum(0, this.height), 1, 0, 2 * Math.PI)
this.ctx.fill()
}
let formula = ''; // 公式字符串
this.num1 = Math.floor(Math.random() * this.range);
this.num2 = Math.floor(Math.random() * this.range);
this.symbol = this.operator[Math.floor(Math.random() * 2)];
console.log(this.num1, this.num2, this.symbol)
if (this.symbol === '+') {
formula = `${this.num1}+${this.num2}=?`
this.result = this.num1 + this.num2;
} else {
if (this.num1 >= this.num2) {
formula = `${this.num1}-${this.num2}=?`
} else {
formula = `${this.num2}-${this.num1}=?`
}
this.result = Math.abs(this.num1 - this.num2);
}
console.log(formula)
for (let i = 0; i < formula.length; i++) {
// 隨機生成字體顏色
this.ctx.fillStyle = this.randomColor(50, 160);
// 隨機生成字體大小(0.5 - 0.75)高的范圍
this.ctx.font = this.randomNum(this.height * 2 / 4, this.height * 3 / 4) + 'px SimHei';
// 字體對齊位置
this.ctx.textBaseline = 'top';
let x = 20 + i * (this.width / formula.length);
let y = this.randomNum(5, this.height / 4);
this.ctx.fillText(formula[i], x, y);
}
},
randomColor (min, max) {
let r = this.randomNum(min, max)
let g = this.randomNum(min, max)
let b = this.randomNum(min, max)
return 'rgb(' + r + ',' + g + ',' + b + ')'
},
randomNum (min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
reset () {
this.result = 0;
this.inputValue = '';
this.state = 'active';
this.drawFormula();
},
verify () {
console.log('輸入>>>', parseInt(this.inputValue))
console.log('生成>>>', this.result)
console.log(parseInt(this.inputValue) === this.result)
let res = parseInt(this.result) === parseInt(this.inputValue);
this.state = res ? 'success' : 'fail';
this.$emit('verify', res);
}
}
}
Vue.createApp(App).mount('#app');
解析:先獲取畫布和畫筆,然后使用fillRect()
方法渲染隨機顏色背景,接下來最重要的部分就是隨機生成表達式并使用fillText()
方法繪制隨機字符,然后使用stroke()
方法繪制線條,使用fill()
方法繪制隨機分布的小圓點,最后驗證表達式。
結尾
上面就是【計算驗證碼】的實現原理,代碼是使用vue編寫的小demo,可能存在一些兼容性問題,也沒有封裝成組件,但是具有一些參考意義,用于生產可以自己去封裝成組件使用,完整的代碼在我的GitHub倉庫
本文是筆者總結編撰,如有偏頗,歡迎留言指正,若您覺得本文對你有用,不妨點個贊~