<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>cannvs验证码</title>
<style>
#canvas {
cursor: pointer;
margin-top: 100px;
margin-left: 400px;
/* border: 1px solid red; */
}
body {
background-color: #ccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="140" height="50"></canvas>
<!-- <input type="text" placeholder="输入验证码" onclick="yanzhengmaEvent()"> -->
</body>
<script>
var canvas = document.querySelector("#canvas");
// console.log(canvas);
var cxt = canvas.getContext('2d');//绘图上下文环境
let yanzhengma = []
//绘制验证码图片
draw();
canvas.onclick = function(){
// console.log('1');
draw();
};
function draw(){
// 绘制一个颜色随机的矩形
yanzhengma=[]
cxt.beginPath();
cxt.fillStyle = randColor(170,250);//把颜色放到一个方法
cxt.fillRect(0,0,140,50);
cxt.closePath();
var data = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789';
for(var i = 0; i <= 90; i +=30){//四位验证码
var c = data[randNum(0,data.length - 1)];
yanzhengma.push(c)
console.log(yanzhengma)
cxt.beginPath();
cxt.fillStyle = randColor(60,160);
cxt.font = randNum(15,40) + 'px SimHei';
cxt.fillText(c, i + randNum(0,15),randNum(15,30));//[0,15) [30,45) [60,75) [90,115)
cxt.closePath();
}
//渲染干扰线
for(var j = 0; j < 10; j ++){
cxt.beginPath();
cxt.moveTo(randNum(0,140), randNum(0,140));
cxt.lineTo(randNum(0,140), randNum(0,140));
cxt.strokeStyle = randColor(60,120);
cxt.stroke();
}
for(var i = 0; i < 10; i ++){
cxt.beginPath();
cxt.strokeStyle = randColor(50,130);
cxt.arc(randNum(0,130),randNum(0,30),randNum(1,3),0,2*Math.PI);
cxt.stroke();
cxt.closePath();
}
}
function randColor(min,max){//max+1是取不到的,但是max是可以取到的,所以向下取整刚好取到[min,max]。
var r = Math.floor(Math.random()*(max-min + 1)+min);//Math.random * (max- min)==>[o,min)变成[min,max-min]的范围
var g = Math.floor(Math.random()*(max-min + 1)+min);
var b = Math.floor(Math.random()*(max-min + 1)+min);
return 'rgb('+r+','+g+','+b+')';
}
function randNum(min,max){
var num = Math.floor(Math.random()*(max-min + 1)+min);
return num;
console.log(num);
}
function yanzhengmaEvent(){
if(yanzhengma == [])return;
yanzhengma.forEach(function(res,index){
if(res == res[idnex]){
}
})
}
</script>
</html>
cannvs验证码
最新推荐文章于 2022-07-31 23:03:09 发布