首页 > 代码库 > 画布实现验证码
画布实现验证码
1,html部分
<canvas id="vCode" class="vCode" width="100" height="40"></canvas>
2,js部分
//生成验证码 function createVCode() { var codeString = ‘0,1,2,3,4,5,6,7,8,9‘; codeString += ‘,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z‘; codeString += ‘,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,t,z‘ var codeArr = codeString.split(‘,‘); var codeData = http://www.mamicode.com/[];>
canvas渲染
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 + ‘)‘; } //显示验证码 function renderCode(codeData) { console.log(codeData); var canvas = document.getElementById(‘vCode‘); var width = canvas.width; var height = canvas.height; var ctx = canvas.getContext(‘2d‘); ctx.fillStyle = randomColor(180, 240); ctx.fillRect(0, 0, width, height); ctx.textBaseline = ‘bottom‘; for (var i = 0; i < codeData.length; i++) { ctx.fillStyle = randomColor(30, 100); ctx.font =‘bold ‘+randomNum(22, 36) + ‘px Arail‘; var x = 10 + i * 16; var y = randomNum(30, 40); var deg = randomNum(-20, 20); ctx.translate(x, y); ctx.rotate(deg * Math.PI / 180); ctx.fillText(codeData[i], 0, 0); ctx.rotate(-deg * Math.PI / 180); ctx.translate(-x, -y); } for (var j = 0; j < 5; j++) { ctx.strokeStyle = randomColor(40, 180); ctx.beginPath(); ctx.moveTo(randomNum(0, width), randomNum(0, height)); ctx.lineTo(randomNum(0, width), randomNum(0, height)); ctx.stroke(); } for(var k =0;k<100;k++){ ctx.fillStyle = randomColor(0,255); ctx.beginPath(); ctx.arc(randomNum(0,width),randomNum(0,height),1,0,2*Math.PI); ctx.fill(); } }
画布实现验证码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。