<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="myCanvas" width="100" height="30"></canvas>
<br />
<input type="text" name="" id="test1"><br />
<div id="test2"></div>
</body>
<script type="text/javascript">
class mathCode{
constructor(id,value) {
this.id = id;
this.value = value;
this.code = null;
}
// 生成一個隨機色
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);
}
// 生成隨機碼
createCode() {
this.code = '';
//驗證碼的長度
let codeLength = 4;
const checkCode = document.getElementById(this.id);
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);
this.code += codeChars[charNum];
}
this.value = this.code;
if (checkCode) {
this.drawVerify();
}
}
// 繪製驗證碼圖形
drawVerify() {
const cEle = document.getElementById(this.id);
const value = this.value;
this.code = value;
const [ctx, width, height] = [cEle.getContext('2d'), cEle.width, cEle.height];
// 清空畫布
ctx.clearRect(0, 0, width, height);
// 繪製背景色
ctx.fillStyle = this.randomColor(180, 240);
ctx.fillRect(0, 0, width, height);
// 填充字體
ctx.font = '30px Arial';
ctx.fillStyle = this.randomColor(50, 160);
ctx.fillText(value, 18, 25);
// 繪製干擾線
for (var i = 0; i < 10; i++) {
ctx.strokeStyle = this.randomColor(40, 180);
ctx.beginPath();
ctx.moveTo(this.randomNum(0, width), this.randomNum(0, height));
ctx.lineTo(this.randomNum(0, width), this.randomNum(0, height));
ctx.stroke();
}
// 繪製干擾點
for (var i = 0; i < 30; i++) {
ctx.fillStyle = this.randomColor(0, 255);
ctx.beginPath();
ctx.arc(this.randomNum(0, width), this.randomNum(0, height), 1, 0, 2 * Math.PI);
ctx.fill();
}
}
// 驗證
/* inputId 輸入框ID, warnId 提示內容ID */
validateCode(inputId,warnId) {
const [inputCode, warnToast] = [document.getElementById(inputId).value, document.getElementById(warnId)];
if (inputCode.length <= 0) {
warnToast.innerHTML = '請輸入驗證碼!';
} else if (inputCode.toUpperCase() != this.code.toUpperCase()) {
warnToast.innerHTML = '驗證碼錯誤';
this.createCode();
} else {
warnToast.innerHTML = '驗證碼正確!';
}
}
}
const Math1 = new mathCode("myCanvas","H6G4");
Math1.drawVerify();//生成二維碼
Math1.validateCode();//校驗
</script>
</html>