刚刚开始接触canvas,写个验证码小功能练练手,实现效果图如下:
主要代码如下:
html
刚刚开始接触canvas,写个验证码小功能练练手,实现效果图如下:
主要代码如下:
html
css
.inputBox {
width: 345px;
margin: 0 auto 10px;
position: relative;
}
.inputBox .inputCaptcha {
display: inline-block;
height: 50px;
width: 86%;
text-indent: 1em;
border: 1px solid #ddd;
border-radius: 5px;
}
.inputBox .captchaIcon {
display: none;
position: absolute;
top: 50%;
right: 0px;
margin-top: -16px;
width: 32px;
height: 32px;
background-size: 100% 100%;
}
.errorText {
width: 345px;
margin: 0 auto;
font-size: 12px;
color: red;
display: none;
}
.canvasBox {
width: 345px;
margin: 10px auto;
position: relative;
}
border-radius: 10px;
}
.canvasBox .refresh {
width: 34px;
height: 34px;
position: absolute;
right: 0px;
top: 50%;
margin-top: -17px;
border: 0;
border-radius: 6px;
background-image: url('./images/update.png');
background-size: cover;
}
.captchaSubmit {
padding: 10px 20px;
background-color: #62b900;
border: 0;
font-size: 20px;
border-radius: 5px;
color: #fff;
}
js
createCanvas();
//验证输入的验证码与图中验证码时候相等
function captcha(e){
if(e == value){
return true;
}
else{
return false;
}
}
//点击提交按钮时的结果
function showResult(){
var inputValue = $('.inputCaptcha').val();
if(inputValue == '' ||inputValue == null || inputValue == 'undefined'){
$('.errorText').css({display:'inline-block'}).html('验证码不能为空,请重新输入!');
$('.captchaIcon').css({display:'inline-block',backgroundImage:"url('./images/false.png')"});
}else{
var flag = captcha(inputValue);
if(!flag){
$('.errorText').css({display:'inline-block'}).html('验证码错误,请重新输入!');
$('.captchaIcon').css({display:'inline-block',backgroundImage:"url('./images/false.png')"});
}else{
$('.captchaIcon').css({display:'inline-block',backgroundImage:"url('./images/true.png')"});
}
}
}
$('.captchaSubmit').click(showResult);//提交
$('.refresh').click(createCanvas);//刷新
//点击input框
$('.inputCaptcha').focus(function(){
$('.errorText').add($('.captchaIcon')).fadeOut(100);
})