html
<!-- 图形容器 -->
<canvas id="canvas" width="100" height="43" onclick="draw()"
style="border: 1px solid #ccc;border-radius: 5px;">
</canvas>
看不清?点击<a href='javaScript:void(0)' onclick="draw()">换一个</a>
js
//验证码图形生成
var show_num = [];
function draw() {
//jquery对canvas对象无法获取,原生js可以解决
var canvas_width=document.getElementById('canvas').clientWidth;
var canvas_height=document.getElementById('canvas').clientHeight;
var canvas = document.getElementById("canvas");//获取到canvas的对象,画布
var context = canvas.getContext("2d");//画笔
//画布范围
canvas.width = canvas_width;
canvas.height = canvas_height;
//字符集
var sCode = "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,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
var aCode = sCode.split(",");
var aLength = aCode.length;//获取到数组的长度
for (var i = 0; i <= 3; i++) {
//向下取整
var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
var txt = aCode[j];//得到随机的一个字符
show_num[i] = txt;
var x = 10 + i * 20;//文字在canvas上的x坐标
var y = 20 + Math.random() * 8;//文字在canvas上的y坐标
//字体样式大小
context.font = "23px 微软雅黑";
//书写位置位移
context.translate(x, y);
//旋转
context.rotate(deg);
//填充的样式
context.fillStyle = randomColor();
//填充的字符,位置
context.fillText(txt, 0, 0);
//重置书写位置(上面的xy与循环中的i有关)
context.rotate(-deg);
context.translate(-x, -y);
}
//干扰项
for (var i = 0; i <= 5; i++) { //验证码上显示线条
context.strokeStyle = randomColor();
//路线开始
context.beginPath();
//起点
context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
//终点
context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
//关闭路线
context.closePath();
//绘制
context.stroke();
}
for (var i = 0; i <= 30; i++) { //验证码上显示小点
context.strokeStyle = randomColor();
context.beginPath();
var x = Math.random() * canvas_width;
var y = Math.random() * canvas_height;
//圆心x,y,半径,起始,终点
context.arc(x,y,1,0,2*Math.PI);
// context.moveTo(x, y);
// context.lineTo(x + 1, y + 1);
context.closePath();
context.stroke();
}
//得到随机的颜色值
function randomColor() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
// return "rgb(" + r + "," + g + "," + b + ")";
return`rgb(${r},${g},${b})`;
}
//
alert("验证码:"+show_num.join(""));
return show_num;
}
$(document).ready(function(){
//初始化验证码
draw();
)}