Canvas生成数字图形验证码,只需一个js文件!!!
登录页面往往会有图形验证码,有时候后台会返回,有时候后台并没有做这个功能,为了方便就需要我们前端人员来做图形验证码。今天只需要一个js文件就可以实现这个功能!
首先,我们要先准备一个容器
<script src="./captcha.js"></script>
<div id="captchaImage" style="width: 80px;height: 20px;"></div>
<input type="text" id="code_input" value="" placeholder="请输入验证码"/><button id="my_button">验证</button>
稍微添加一些样式
#captchaImage {
border: 2px solid transparent;
margin-bottom: 10px;
overflow: hidden;
border-image:linear-gradient(to right,#94C5B0,#66BDC0) 1 10
}
然后创建一个chptcha.js文件
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
let size = 4;
function Captcha(options) {
this.options = {
id: "",
canvasId: "verifyCanvas",
width: "50",
height: "30",
code: "",
}
if (Object.prototype.toString.call(options) == "[object Object]") {
for (var i in options) {
this.options[i] = options[i];
}
} else {
this.options.id = options;
}
this.options.numArr = "0,1,2,3,4,5,6,7,8,9".split(",");
this._init();
this.refresh();
}
Captcha.prototype = {
_init: function () {
var con = document.getElementById(this.options.id);
var canvas = document.createElement("canvas");
this.options.width = con.offsetWidth > 0 ? con.offsetWidth : "100";
this.options.height = con.offsetHeight > 0 ? con.offsetHeight : "30";
canvas.id = this.options.canvasId;
canvas.width = this.options.width;
canvas.height = this.options.height;
canvas.style.cursor = "pointer";
canvas.innerHTML = "您的浏览器版本不支持canvas";
con.appendChild(canvas);
var parent = this;
canvas.onclick = function () {
parent.refresh();
}
},
refresh: function () {
this.options.code = "";
var canvas = document.getElementById(this.options.canvasId);
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
} else {
return;
}
ctx.textBaseline = "middle";
ctx.fillStyle = 'rgb(247,253,251)';
ctx.fillRect(0, 0, this.options.width, this.options.height);
var txtArr = "0,1,2,3,4,5,6,7,8,9".split(",");
for (var i = 1; i <= size; i++) {
var txt = txtArr[randomNum(0, txtArr.length)];
this.options.code += txt;
ctx.font = '25px SimSun'
ctx.fillStyle = 'rgb(93,151,126)';
var x = this.options.width / (size + 1) * i;
var y = this.options.height / 2;
ctx.translate(x, y);
ctx.fillText(txt, -6, -3);
ctx.translate(-x, -y);
}
},
validate: function (code) {
var v_code = this.options.code;
if (code == v_code) {
return true;
} else {
this.refresh();
return false;
}
}
}
前面我们在容器的html引入了captchat.js,接下来是使用,同样写容器的html中
<script>
var captchaCode = new Captcha("captchaImage");
document.getElementById("my_button").onclick = function(){
var res = verifyCode.validate(document.getElementById("code_input").value);
if(res){
alert("验证正确");
}else{
alert("验证码错误");
}
}
</script>
效果图如下 这里加了验证和点击刷新验证码的功能! 这个仅供大家参考,如果想要实现字母类型的验证码或者是字母数字混合类型的验证码,需要在captcha.js修改相关参数即可。
|