1、功能分析前端
圖形驗證碼由驗證碼、干擾線、干擾點組合而成canvas
驗證碼由數字和字母隨機組合造成微信
每次切換驗證碼,驗證碼字體顏色和背景顏色變化dom
2、實現思路字體
生成一個隨機色,用於切換驗證碼時控制字體顏色和背景顏色ui
生成一個隨機數,用於改變顏色的 rgb 值和繪製干擾線與干擾點spa
生成一個由數字和字母組合而成的隨機碼code
將隨機數、干擾線、干擾點繪製在 canvas 畫布上get
因爲圖形驗證碼是會刷新的,因此下一次刷新的時候要確保畫布是空的,纔不會出現上一次繪製的圖形,所以,要在繪製圖形以前,清空畫布input
驗證:經過對比輸入的值和生成的隨機碼,驗證是否輸入正確
3、示例
let code;
// 生成一個隨機色
function randomColor(min, max) {
let r = randomNum(min, max);
let g = randomNum(min, max);
let b = randomNum(min, max);
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
// 生成一個隨機數
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
// 生成隨機碼
function createCode() {
code = '';
//驗證碼的長度
let codeLength = 4;
const checkCode = document.getElementById('myCanvas');
const codeChars = [];
// 驗證碼所需數字和字母的集合
for (let i = 0; i < 26; i++) {
if (i < 10) {
codeChars.push(String.fromCharCode(i + 48));
}
codeChars.push(String.fromCharCode(i + 97));
codeChars.push(String.fromCharCode(i + 65));
}
// 組合數字和字母
for (let i = 0; i < codeLength; i++) {
let charNum = Math.floor(Math.random() * 52);
code += codeChars[charNum];
}
if (checkCode) {
drawVerify(checkCode, code);
}
}
// 繪製驗證碼圖形
function drawVerify(cEle, value) {
const [ctx, width, height] = [cEle.getContext('2d'), cEle.width, cEle.height];
// 清空畫布
ctx.clearRect(0, 0, width, height);
// 繪製背景色
ctx.fillStyle = randomColor(180, 240);
ctx.fillRect(0, 0, width, height);
// 填充字體
ctx.font = '30px Arial';
ctx.fillStyle = randomColor(50, 160);
ctx.fillText(value, 20, 40);
// 繪製干擾線
for (var i = 0; i < 2; i++) {
ctx.strokeStyle = randomColor(40, 180);
ctx.beginPath();
ctx.moveTo(randomNum(0, width), randomNum(0, height));
ctx.lineTo(randomNum(0, width), randomNum(0, height));
ctx.stroke();
}
// 繪製干擾點
for (var i = 0; i < 30; i++) {
ctx.fillStyle = randomColor(0, 255);
ctx.beginPath();
ctx.arc(randomNum(0, width), randomNum(0, height), 1, 0, 2 * Math.PI);
ctx.fill();
}
}
// 驗證
function validateCode() {
const [inputCode, warnToast] = [document.getElementById('inputCode').value, document.getElementById('warnToast')];
if (inputCode.length <= 0) {
warnToast.innerHTML = '請輸入驗證碼!';
} else if (inputCode.toUpperCase() != code.toUpperCase()) {
warnToast.innerHTML = '驗證碼錯誤';
createCode();
} else {
warnToast.innerHTML = '驗證碼正確!';
}
}
複製代碼
更多幹貨,可關注個人微信公衆號:薛定諤的前端,按期接收我原創的前端文章