对验证码组件进行封装
参考了这篇文章
<canvas id="canvas" width="120" height="30" style="cursor: pointer;"></canvas>
var cas=document.querySelector('#canvas');
var ctx=cas.getContext('2d'); //构建绘图环境
cas.onclick = randomCode;
position={x:0,y:0,w:120,h:30};//位置对象
needDisturbPoint = true;//是否需要干扰点
needDisturbLine = true;//是否需要干扰线
randCode = "";//始终返回最新的验证码
randomCode();
function randomCode(){
//position Object x:起始横坐标 y:起始纵坐标 w:矩形宽 h:矩形高
//needDisturbPoint 表示需要干扰点,不推荐
//needDisturbLine 表示需要干扰线,推荐
function randNum(min,max){
//获取随机数
return Math.floor(Math.random()*(max-min+1)+min);
}
function randColor(min,max){
//获取一个随机颜色
var r = randNum(min,max);
var g = randNum(min,max);
var b = randNum(min,max);
return 'rgb('+r+','+g+','+b+')';
}
function drawRect(x,y,w,h){
//绘制一个带颜色的矩形
ctx.clearRect(x,y,w,h);
ctx.fillStyle=randColor(170,250); //这里背景色的取值范围为[170,250],颜色比较适中
ctx.fillRect(x,y,w,h); //绘制矩形
}
function get4RandomCode(){
var code = "";
var data='qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
for(var i=0;i<120;i+=30){ //循环四次,取四个字
var c=data[randNum(0,data.length-1)]; //index为随机数,[0,data.length-1] 取字(随机)
code = code + c;
ctx.fillStyle=randColor(60,160); //字体颜色
ctx.font=randNum(15,40)+'px SimHei'; //字体大小,字体
ctx.fillText(c,i+randNum(5,12),randNum(15,30)); //字体填充(字内容,x轴,y轴)位置都是随机
}
return code.toUpperCase();
}
function getDisturbLine(){
for (var i=0;i<10;i++) {
ctx.beginPath(); //路径开始,子路经的集合
ctx.moveTo(randNum(0,120),randNum(0,120));//起始点(x,y),都随机
ctx.lineTo(randNum(0,120),randNum(0,120));//终止点(x,y)
ctx.strokeStyle=randColor(60,160);//路径的颜色
ctx.stroke(); //将上面的两个点连接起来
}
}
function getDisturbPoint(){
ctx.beginPath(); //路径开始
ctx.arc(randNum(0,120),randNum(0,30),randNum(1,5),0,2*Math.PI);//画圆(x,y,z,0,2*Math.PI) x坐标,y坐标,半径,完整圆
ctx.strokeStyle=randColor(60,160);
ctx.stroke();
ctx.fill();
}
drawRect(position.x,position.y,position.w,position.h);
var code = get4RandomCode();
randColor(0,255);
if(needDisturbLine) getDisturbLine();
if(needDisturbPoint) getDisturbPoint();
randCode = code;
console.log(randCode);
}