<!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>
<style>
div {
display: flex;
margin: 50px 700px;
}
input {
width: 100px;
height: 20px;
outline: 0;
margin-right: 10px;
}
canvas {
background-color: #b0aa93;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="box">
<input type="text">
<canvas width="100" height="30"></canvas>
<button>提交</button>
</div>
<script>
let canvas = document.getElementsByTagName('canvas')[0];
let ctx = canvas.getContext('2d');
let codeRange=[];
let str='';
function code() {
// 清空画布
ctx.clearRect(0,0,100,30);
// 画干扰线条
for (let i = 0; i < 4; i++) {
ctx.beginPath();
ctx.moveTo(getRandom(0, 100), getRandom(0, 30));
ctx.lineTo(getRandom(0, 100), getRandom(0, 30));
ctx.strokeStyle = getRandomColor();
ctx.lineWidth = getRandom(1, 3)
ctx.stroke();
ctx.closePath;
}
// 画干扰点
for (let i = 0; i < 30; i++) {
ctx.beginPath();
ctx.arc(getRandom(0, 100), getRandom(0, 30), 1.5, 0, Math.PI * 2)
ctx.fillStyle = getRandomColor();
ctx.fill();
ctx.closePath();
}
// 画验证码
function getCodeRange() {
// let codeRange = [];
for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
codeRange.push(String.fromCharCode(i));
}
for (let i = "a".charCodeAt(0); i <= "z".charCodeAt(0); i++) {
codeRange.push(String.fromCharCode(i));
}
for (let i = "0".charCodeAt(0); i <= "9".charCodeAt(0); i++) {
codeRange.push(String.fromCharCode(i));
}
arr=codeRange;
this.codeRange = codeRange;
let num = 10;
let sizeRandom = getRandom(25, 40); // 随机字体大小
// 随机生成四个验证码
str='';
for (let i = 0; i < 4; i++) {
// 随机数组的下标
var index = parseInt(getRandom(0, codeRange.length));
// 随机旋转度数
let deg = Math.PI / 180 * getRandom(-40, 40);
ctx.font = sizeRandom + 'px 宋体';
ctx.fillStyle = getRandomColor();
ctx.save(); //保存当前路径
ctx.beginPath();
ctx.translate(num, 12)
ctx.rotate(deg);
ctx.textBaseline = 'middle';
ctx.fillText(codeRange[index], 0, 0);
ctx.closePath();
ctx.restore();
num += 20;
str= str.concat(codeRange[index]);
}
};
getCodeRange();
}
code();
// console.log(str);
canvas.onclick = function () {
code();
}
// 获取input值验证验证码
let ipt=document.getElementsByTagName('input')[0];
let btn=document.getElementsByTagName('button')[0].onclick=function(){
if(ipt.value==str){
alert("验证码正确!!!");
}
}
function getRandom(min, max) {
return Math.random() * (max - min) + min;
};
function getRandomColor() {
return `rgb(${getRandom(0,255)},${getRandom(0,255)},${getRandom(0,255)})`;
}
</script>
</body>
</html>
【画布】写一个验证码
最新推荐文章于 2022-12-06 09:29:21 发布