目录

项目实现图片GIF

项目思想

详细版(带大量解释)

HTML代码

CSS代码

JS代码

简洁版(不带解释)

HTML代码

CSS代码

JS代码

使用图片


项目实现图片GIF

项目思想

把组成验证码的所有字符放入一个数组,然后通过Math.random随机选取字符组成验证码,放入画布中,监听点击按钮进行刷新和提交,比较返回结果。

详细版(带大量解释)

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script>
    <link rel="stylesheet" href="loginVerify.css">
</head>
<body>
    <div class="wrapper">
        <!-- 注意不要用box的after伪元素做正确和错误的图标,这样无法用jQuery和doom选中 -->
        <div class="box">
            <input class="input" type="text">
            <span class="tfPhoto"></span>          
        </div>
        <p class="tfPhrase">验证码错误,请重新输入</p>
        <div class="canvas">
            <canvas id="myCanvas" width="300px" height="80px"></canvas>
            <span class="refresh"></span>
        </div>
        <button class="submit" type="submit">submit</button>
    </div>
    <script src="loginVerify.js"></script>
</body>
</html>

CSS代码

*{
    margin: 0;
    padding: 0;
}
.wrapper{
    width:380px;
    border:1px solid black;
    margin:25px;
}
/* 设置文本框 */
.input{
    width: 270px;
    height: 16px;
    line-height: 16px;
    margin:15px 10px 15px 15px ;
    border: 1px solid black;
    font-size: 16px;
    padding: 10px 15px;
}
.box{
    position: relative;
}
/* 展示对错图片 */
.tfPhoto{
    display: none;
    width: 32px;
    height: 32px;
    background: url(img/yes.jfif);
    background-size: 100% 100%;
    /* 使图片大小铺满背景 ,第一个是宽度,第二个是高度*/
    position: absolute;
    top:16px;
    /* 在浏览器中调整定位 */
}
/* 正确错误短语 */
.tfPhrase{
    color:red;
    font-size: 12px;
    height: 12px;
    line-height: 12px;
    margin-left: 15px;
    display: none;
}
/* 显示验证码画布画布 */
.canvas{
    margin:25px 10px 20px 15px;
    width: 300px;
    height: 80px;
    border: 1px solid black;
    position: relative;
    background: url(img/bg.jpg);
    background-size: 100%;
    /* 方法二利用CSS设置背景图片,画图时,画图时不需要填充整个样式图片了 */
}
/* 刷新图标 */
.refresh{
    display: inline-block;
    width: 32px;
    height: 32px;
    background: url(img/refresh.jpg);
    background-size: 100% 100%;
    position: absolute;
    top:28%;
    right: -44px;
    cursor: pointer;
    /* 鼠标放上去有形状的变化 */
}
.submit{
    margin: 5px 0 20px 15px;
    width: 90px;
    height: 40px;
    font-size: 18px;
    border-radius: 10px;
    cursor: pointer;
}

JS代码

// 首先把验证码包含的所有字符放入一个数组数组中,然后用随机数取几个。注意数字用字符串的形式,之后好做连接。
var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// 65~90为A~Z,97~122为a~z
for (var i = 65; i < 123; i++) {
    if (i > 90 && i < 97) {
        continue;
    }
    arr.push(String.fromCharCode(i));
    // String.fromCharCode(number1,number2,...,numbern)
    // 返回number1,number2,...,numbern在Unicode编码中分别对应的字符拼接成的字符串。什么都不传时返回空串。
}
var strCode = '';
//避免产生undefined+字符串的形式
console.log(arr);
function createCanvas() {
    strCode = '';
    // 每次运行初始化
    // 生成5位数的验证码,注意Math.random是可以取到0的,但不能取到1,我们需要产生0~61的数组索引,所以乘以62向下取整即可
    for (var i = 0; i < 5; i++) {
        strCode += arr[Math.floor(Math.random() * 62)]
    }
    console.log(strCode);
    var myCanvas = document.getElementById('myCanvas');
    var ctx = myCanvas.getContext('2d');
    // 方法一:简洁版采用的方法,直接在canvas中设置填充图片,需要注意的是实际图片宽高要完全符合填充大小,不然填充的部分将只会截取部分填充,
    // 即无法做到缩放图片,哪怕设置oImg的图片宽高,也还是会在实际的图片上截取画布宽高的内容
    // var oImg = new Image();
    // oImg.src = 'bg.png';
    // console.log(oImg.width+oImg.height);
    // oImg.onload = function(){		
    // 	var pattern = ctx.createPattern(oImg,'no-repeat');
    // 	ctx.fillStyle = pattern;
    // 	ctx.fillRect(0,0,myCanvas.width,myCanvas.height);
    // }
    // 方法二:利用CSS在canvas的父集上设置背景图片,这样可以不管实际图片大小,直接放缩,然后在canvas中便只需要设置画笔就行,不需要再填充内容了。
    ctx.textAlign = 'center';
    // 默认是star,它会从ctx.fillText(strCode,100,60);的100px开始往后填充,当变成center时,它会文本strCode关于100px的位置居中,即向左平移了1/2的文本宽度。
    ctx.fillStyle = 'black';
    // 设置画笔颜色,也可以像方法一中一样自创画笔样式,来填充图片
    ctx.font = '46px Roboto Slab';
    // 设置画笔字体和大小
    ctx.setTransform(1, -0.12, 0.3, 1, 0, 12);
    // ctx.setTransform(a,-b,c,d,e,f),其中a代表水平缩放绘图;b代表水平倾斜绘图;c代表垂直倾斜绘图;d代表垂直缩放绘图;e代表水平移动绘图;f代表垂直移动绘图
    ctx.fillText(strCode, 100, 60);
    //
    ctx.stroke();
    return ctx;
}
ctx = createCanvas();
// 刷新功能实现
$('.refresh').on('click', function () {
    ctx.clearRect(0,0,300,80);
    // 去除上次的画图部分,代表擦除(0,0)(300,80)为对角线的矩形部分内容,方法一由于每次都会重新绘制背景图片所以不需要考虑重复绘制的问题。
    createCanvas();
    // 去除验证文字
    $('.tfPhrase').css('display','none');
    // 清除验证图片
    $('.tfPhoto').css('display','none');
    // 清除文本框内容
    $('.input').val('');
})
// 验证功能实现
$('.submit').on('click', function () {
    if($('.input').val().toLowerCase()==strCode.toLowerCase()){
        // 如果验证码正确,更换图片
        $('.tfPhoto').css({
            background:'url("yes.jfif")',
            display:'inline-block',
            backgroundSize:'100%'
        });
        // 显示文字
        $('.tfPhrase').css('display','block').html('验证码正确')
    }else{
        // 如果验证码错误,更换图片
        $('.tfPhoto').css({
            background:'url("false.jpg")',
            display:'inline-block',
            backgroundSize:'100%'
        });
        // 显示文字
        $('.tfPhrase').css('display','block').html('验证码错误,请重新输入')
        ctx.clearRect(0,0,300,80);
        createCanvas();   
    }
})

简洁版(不带解释)

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="demo.css">
	<script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script>
	<title>Document</title>
</head>
<body>
	<div class="wrapper">
		<div class="inputBox">
			<input type="input" placeholder="请输入验证码">
			<span></span>
		</div>
		<p class="error"></p>
		<div class="canvasBox">
			<div class="imgBox">
				<canvas id="myCanvas" width="300px" height="80px"></canvas>
			</div>
			<input type="button" class="refresh">
		</div>
		<button class="submit">submit</button>
		<script src="demo.js"></script>
	</div>
</body>
</html>

CSS代码

*{
	margin: 0;
	padding: 0;
}
.wrapper{
	margin: 30px;
	width: 345px;
	padding: 15px;
	border: 1px solid #ccc;
	border-radius: 5px;
}
.inputBox{
	position: relative;
}
.inputBox input{
	display: inline-block;
	width: 300px;
	outline: none;
	padding: 15px;
	border-radius: 5px;
	border: 1px solid #ccc;
	box-sizing: border-box;
}
.inputBox span{
	position: absolute;
	width: 32px;
	height: 32px;
	background: url('yes.jfif');
	background-size: 100%;
	display: none;
}
.error{
	color:red;
	margin-top: 10px;
	font-size: 12px;
	display: none;
}
.canvasBox{
	position: relative;
	margin-top: 15px;

}
.canvasBox .imgBox{
	width: 300px;
	height: 80px;
	border: 1px solid #ccc;
	border-radius: 5px;

}
.canvasBox .refresh{
	position: absolute;
	right: 0;
	top: 50%;
	display: inline-block;
	width: 32px;
	height: 32px;
	background: url('refresh.jpg');
	background-size: 100%;
	margin-top: -16px; 
	border:0;
	cursor: pointer;
}
.submit{
	padding: 10px 20px;
	border: 0;
	background-color: greenyellow;
	color: #fff;
	font-size: 18px;
	margin-top: 15px;
	border-radius: 5px;
	cursor: pointer;
}

JS代码

var arr = [0,1,2,3,4,5,6,7,8,9,];
for(var i = 65;i < 122;i++){
	if(i > 90 && i < 97){
		continue;
	}
	arr.push(String.fromCharCode(i));
}
var value;
function createCanvas(){
	var canvasStr = '';
	value ='';
	for(var i = 0; i < 6;i++){
		a = arr[Math.floor(Math.random()*arr.length)];
		canvasStr += a + ' ';
		value += a;
	}
	var myCanvas = document.getElementById('myCanvas');
	var ctx = myCanvas.getContext('2d');
	var oImg = new Image();
	oImg.src = 'bg.png';
	console.log(oImg.width+oImg.height);
	oImg.onload = function(){		
		var pattern = ctx.createPattern(oImg,'no-repeat');
		ctx.fillStyle = pattern;
		ctx.fillRect(0,0,myCanvas.width,myCanvas.height);
		ctx.textAlign = 'center';
		ctx.fillStyle = '#FFF';
		ctx.font = '46px Roboto Slab';
		ctx.setTransform(1,-0.12,0.3,1,0,12);
		ctx.fillText(canvasStr,myCanvas.width/2,60);
	}
	console.log(value);
}
createCanvas();
$('.submit').on('click',function(){
	showResult();
});
$('.refresh').on('click',function(){
	$('.inputBox input').val('');
	$('.error').css('display','none');
	$('.inputBox span').css('display','none');
	createCanvas();
})
function showResult(){
	var inputValue = $('.inputBox input').val();
	if(value.toLowerCase() == inputValue.toLowerCase()){		
		$('.inputBox span').css({
			display:'inline-block',
			background: 'url("yes.jfif")',
			backgroundSize: '100%'
		});
		$('.error').css('display','block').html('验证码正确!');
		createCanvas();
	}else{
		
		$('.inputBox span').css({
			display:'inline-block',
			background: 'url("false.jpg")',
			backgroundSize: '100%'
		});
		$('.error').css('display','block').html('验证码错误,请重新输入');
		createCanvas();
	}
}

使用图片

html5手机号码的验证_HTML+CSS+JS

html5手机号码的验证_HTML+CSS+JS_02

html5手机号码的验证_HTML+CSS+JS_03

html5手机号码的验证_canvas制作验证码输入框_04