为方便自己以后项目中使用,在此留一份原生JS实现的图像验证码代码。
-
export function drawAuthCode(id) {
-
var num = [];
-
var canvas = document.getElementById(id);
-
var canvas_width = canvas.offsetWidth;
-
var canvas_height = canvas.offsetHeight;
-
var context = canvas.getContext( "2d");
-
context.clearRect( 0, 0, canvas_width, canvas_height);
-
var sCode = "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
-
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;
-
var txt = aCode[j];
-
num[i] = txt.toLowerCase();
-
var x = 10 + i * 20;
-
var y = 20 + Math.random() * 8;
-
context.font = "bold 26px 微软雅黑";
-
context.translate(x, y);
-
context.rotate(deg);
-
context.fillStyle = randomColor();
-
context.fillText(txt, 0, 0);
-
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.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;
-
context.moveTo(x, y);
-
context.lineTo(x + 1, y + 1);
-
context.stroke();
-
}
-
return num.join( "");
-
}
-
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 + ")";
-
}
-
在需要的页面引入即可
-
//传入一个id为code的容器作为验证码的承载容器
-
var code = drawAuthCode( "code");
-
在此行修改图像验证码中的元素
var sCode = "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
在此行修改图形验证中元素的字体样式
context.font = “bold 26px 微软雅黑”;
在此代码片段修改图形验证码中的线条
-
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.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;
-
context.moveTo(x, y);
-
context.lineTo(x + 1, y + 1);
-
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 + ")";
-
}
-