绝大部分代码来源于韦世东《Python3反爬虫原理与绕过实战》
实现代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>实现字符验证码</title>
</head>
<body>
<canvas id="wordsCanvas">
</canvas>
<script>
var width="200"
var height="40"
var wordsCanvas=document.getElementById('wordsCanvas');
var cvas=wordsCanvas.getContext('2d');
cvas.fillStyle='#CDC8B1';
cvas.fillRect(0,0,width,height);
function randNumber(min,max){
var res=parseInt(Math.random()*(max-min)+min);
return res;
}
function randColor(min,max){
var r=randNumber(min,max);
var g=randNumber(min,max);
var b=randNumber(min,max);
var colorRes="rgb(" + r + "," + g + "," + b + ")";
return colorRes;
}
var fontSize=randNumber(36,40);
var fonts=fontSize+'px Arial';
var letter="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var strs=[];
for (var i=0;i<6;i++){
var single=letter[randNumber(0,letter.length)];
cvas.font=fonts;
cvas.textBaseline='top';
cvas.fillStyle=randColor(30,140);
cvas.save();
cvas.translate(30*i+15,15);
cvas.fillText(single,-15+5,-15);
cvas.restore();
strs.push(single)
}
function cvasInterfere(cvas,width,height){
for(var i=0;i<8;i++){
cvas.beginPath();
cvas.moveTo(randNumber(0,width),randNumber(0,height));
cvas.lineTo(randNumber(0,width),randNumber(0,height));
cvas.strokeStyle=randColor(180,220);
cvas.closePath();
cvas.stroke();
}
for(var i=0;i<80;i++){
cvas.beginPath();
cvas.arc(randNumber(0,width),randNumber(0,height),1,0,2*Math.PI);
cvas.closePath();
cvas.fillStyle=randColor(150,250);
cvas.fill();
}
}
cvasInterfere(cvas,width,height);
function wordsVerifys(){
var codeStr=strs.join('');
var inputCode=document.getElementById('code').value.toUpperCase();
if(inputCode==codeStr){
alert('验证码:'+inputCode+',通过验证。');
}else{
alert('很遗憾,未通过验证');
}
}
</script>
<input type="text" id="code">
<button type="" class="btn btn-default" onclick="wordsVerifys()">登录</button>
</body>
</html>