canvas绘制验证码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制验证码</title>
<style>
body{text-align: center}
canvas{border:1px solid greenyellow}
</style>
</head>
<body>
<h1>canvas绘制验证码</h1>
验证码:<input type="text" id="checkcode" name="checkcode"/>
<canvas width="120" height="40" id="c1">
</canvas>
<button type="submit" onclick="checked()">提交</button>



<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script>
function checked(){
var jValue = myArray.toString().replace(/,/g,"").toLowerCase();
var value = $("#checkcode").val().toLowerCase();
if(jValue==value){
alert("提交成功");
}else{
alert("验证码错误");
}
}

window.onload=function(){
draw();
var  canvas = document.getElementById('c1');
canvas.onclick=function(e){
draw();

}

}
var myArray;
function draw(){
myArray = new Array();

//1.新建一个函数产生随机数
function rn(min,max){
return parseInt(Math.random()*(max-min)+min);
}
//2.新建一个函数产生随机颜色
function rc(min,max){
var r = rn(min,max);
var g = rn(min,max);
var b = rn(min,max);
//return `rgb(${r},${g},${b})`;
//return 'rgb('+r+','+g+','+b+')';
return "rgb("+r+","+g+","+b+")";
}
//3.填充背景颜色,颜色要浅一点
var w=120;
var h=40;
var ctx = c1.getContext("2d");
ctx.fillStyle = rc(180,230);
ctx.fillRect(0,0,w,h);
//4.随机产生字符串
var pool="ABCDEFGHIJKLIMNOPQRSTUVWSYZ1234567890";

for(var i=0;i<4;i++){
var c = pool[rn(0,pool.length)];//随机的字

myArray.push(c);//把生成的验证码放在数组中

var fs = rn(18,40);//字体的大小
var deg = rn(-30,30);//字体的旋转角度
ctx.font = fs+'px Simhei';
ctx.textBaseline = "top";
ctx.fillStyle = rc(80,150);
ctx.save();
ctx.translate(30*i+15,15);
ctx.rotate(deg*Math.PI/180);
ctx.fillText(c,-15+5,-15);
ctx.restore();
}
//5.随机产生5条干扰线,干扰线的颜色要浅一点
for(var i=0;i<5;i++){
ctx.beginPath();
ctx.moveTo(rn(0,w),rn(0,h));
ctx.lineTo(rn(0,w),rn(0,h));
ctx.strokeStyle=rc(180,230);
ctx.closePath();
ctx.stroke();
}
//6.随机产生40个干扰的小点
for(var i=0;i<40;i++){
ctx.beginPath();
ctx.arc(rn(0,w),rn(0,h),1,0,2*Math.PI);
ctx.closePath();
ctx.fillStyle=rc(150,200);
ctx.fill();
}
}
</script>
</body>
</html>
posted @ 2019-03-13 17:03  木子小猿  阅读(224)  评论(0)    收藏  举报