js实现Web验证码

话不多说,直接上代码。

/*
* 这个js是用来产生验证码的
* 可以直接套用,需要主要的是对应的id名字
*/
/*
* 随机产生min到max之间的数
*/
function randomNum(min,max)
{
return Math.floor(Math.random()*(max-min)+min);
}
/*
* 生成随机颜色RGB分量
*/
function randomColor(min,max)
{
var _r = randomNum(min,max);
var _g = randomNum(min,max);
var _b = randomNum(min,max);
return "rgb("+_r+","+_g+","+_b+")";
}

function drawPic(){
//获取到元素canvas
var $canvas = document.getElementById("canvas");
var _str = "0123456789"; //设置随机数库
var _picTxt = ""; //随机数
var _num = 4; //4个随机数字
var _width = $canvas.width; //得到区域宽度和高度
var _height = $canvas.height;
var ctx = $canvas.getContext("2d"); //获取 context 对象,获得一个二维绘图环境,画布
ctx.textBaseline = "bottom"; //文字上下对齐方式--底部对齐
ctx.fillStyle = randomColor(180,240); //填充画布颜色
ctx.fillRect(0,0,_width,_height); //填充矩形--画画
for(var i=0; i<_num; i++){
var x = (_width-5)/_num*i+5;
var y = randomNum(_height/2,_height);
var deg = randomNum(-30,30);
var txt = _str[randomNum(0,_str.length)]; //从所提供的随机数里随机选取一个数
_picTxt += txt; //把得到的随机数加入总随机数里
ctx.fillStyle = randomColor(10,100); //填充随机颜色
ctx.font = randomNum(16,26)+"px SimHei"; //设置随机数大小,字体为SimHei
ctx.translate(x,y); //将当前xy坐标作为原始坐标(0,0)
//ctx.rotate(deg*Math.PI/180); //旋转随机角度deg
ctx.fillText(txt,0,0); //绘制填色的文本
//ctx.rotate(-deg*Math.PI/180);
ctx.translate(-x,-y);
}
/*
* 画四条线
*/
for(var i=0; i<_num; i++){
//定义笔触颜色
ctx.strokeStyle = randomColor(90,180);
ctx.beginPath();
//随机划线--4条路径
ctx.moveTo(randomNum(0,_width), randomNum(0,_height)); //线的起始位置
ctx.lineTo(randomNum(0,_width), randomNum(0,_height)); //线的终止位置
ctx.stroke(); //在画布上绘制确切的路径
}
/*
* 画很多点
*/
for(var i=0; i<_num*10; i++){
ctx.fillStyle = randomColor(0,255);
ctx.beginPath();
//随机画原,填充颜色
ctx.arc(randomNum(0,_width),randomNum(0,_height), 1, 0, 2*Math.PI);
ctx.fill();
}
code=_picTxt;
return _picTxt;//返回随机数字符串

}
/*
* 打开页面直接加载
*/
window.onload = function(){
drawPic();
}

posted @ 2019-12-19 17:13  嫖老板  阅读(438)  评论(0编辑  收藏  举报