jquery canvas绘制图片验证码实例
程序员文章站
2022-07-05 09:13:03
本文实例为大家分享了jquery canvas绘制图片验证码的具体代码,供大家参考,具体内容如下css.identify-code{ position: absolute; right:...
本文实例为大家分享了jquery canvas绘制图片验证码的具体代码,供大家参考,具体内容如下
css
.identify-code{ position: absolute; right: 6px; top: 50%; width: 118px; height: 40px; margin: -21px 0 0 0; }
html
<span id="code" class="identify-code"> <canvas class="show-captcha" id="canvas" style="width: 100%; height: 100%;"></canvas> </span>
js
/**绘制验证码图片**/ function drawpic() { var canvas = document.getelementbyid("canvas"); var width = canvas.width; var height = canvas.height; //获取该canvas的2d绘图环境 var ctx = canvas.getcontext('2d'); ctx.textbaseline ='bottom'; /**绘制背景色**/ ctx.fillstyle = randomcolor(180, 240); //颜色若太深可能导致看不清 ctx.fillrect(0,0,width,height); /**绘制文字**/ var str ='abcefghjklmnpqrstwxy123456789abcefghjklmnpqrstwxy'; var code=""; //生成四个验证码 for(var i = 1;i <= 4; i++) { var txt = str[randomnum(0,str.length)]; code=code+txt; ctx.fillstyle = randomcolor(50,160); //随机生成字体颜色 ctx.font = randomnum(90,110) +'px simhei'; //随机生成字体大小 var x = 10 + i * 50; var y = randomnum(100, 135); var deg = randomnum(-30, 30); //修改坐标原点和旋转角度 ctx.translate(x, y); ctx.rotate(deg * math.pi /180); ctx.filltext(txt,0,0); //恢复坐标原点和旋转角度 ctx.rotate(-deg * math.pi /180); ctx.translate(-x, -y); } /**绘制干扰线**/ for(var i=0;i<3;i++) { ctx.strokestyle = randomcolor(40, 180); ctx.beginpath(); ctx.moveto(randomnum(0,width/2), randomnum(0,height/2)); ctx.lineto(randomnum(0,width/2), randomnum(0,height)); ctx.stroke(); } /**绘制干扰点**/ for(var i=0;i <50;i++) { ctx.fillstyle = randomcolor(255); ctx.beginpath(); ctx.arc(randomnum(0, width), randomnum(0, height),1,0,2* math.pi); ctx.fill(); } return code; } /**生成一个随机数**/ function randomnum(min, max) { return math.floor(math.random() * (max - min) + min); } /**生成一个随机色**/ function randomcolor(min, max) { var r = randomnum(min, max); var g = randomnum(min, max); var b= randomnum(min, max); return "rgb(" + r + "," + g + "," + b + ")"; }
调用实例
$("#code").unbind('click').click(function(e){ e.preventdefault(); createcode(); }); //生成验证码 function createcode(){ verificationcodeerrcount = 0; randomcode = drawpic(); return randomcode; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。