Canvas<文字验证码效果>
2020-03-16 本文已影响0人
誰在花里胡哨
效果图:
20200316.gif因为若是在项目中使用,一般会根据后端返回的信息,前端进行生成验证码,所以此处并没有针对验证码做随机处理。
/* 画布背景色 */
background: #f1f1f1;
let dotNum = 20; //背景小点数量
let lineNum = 4; //背景线条数量
let codeText = "FG2H" //验证码文字
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body,
html {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
margin: 0;
}
.verification_box {
box-sizing: border-box;
display: flex;
}
.code canvas {
display: block;
/* 画布背景色 */
background: #f1f1f1;
}
</style>
</head>
<body>
<div class="verification_box">
<div class="code">
<canvas id="code_canvas" width="150" height="60"></canvas>
</div>
</div>
</body>
<script>
let canvas = document.getElementById("code_canvas");
let ctx = canvas.getContext("2d");
let c_w = canvas.width;
let c_h = canvas.height;
let dotNum = 20; //背景小点数量
let lineNum = 4; //背景线条数量
let codeText = "FG2H" //验证码文字
//随即方法
function random(min, max) {
return Math.random() * (max - min + 1) + min;
}
//定义一个随机颜色
function rndCol() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
}
//画小点
function drawDot() {
for (let i = 0; i < dotNum; i++) {
ctx.beginPath();
ctx.fillStyle = "#cccccc";
ctx.arc(Math.random() * c_w, Math.random() * c_h, 1, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
}
//画线
function drawLine() {
for (let i = 0; i < lineNum; i++) {
let start_x = Math.random() * c_w;
let start_y = Math.random() * c_h;
let end_x = Math.random() * c_w;
let end_y = Math.random() * c_h;
ctx.beginPath();
ctx.strokeStyle = rndCol()
ctx.lineWidth = 2;
ctx.moveTo(start_x, start_y);
ctx.lineTo(end_x, end_y);
ctx.stroke();
ctx.closePath();
}
}
//画文字
function drawText() {
let textArray = codeText.split('');
for (let i = 0; i < textArray.length; i++) {
let fs = random(30, 40);//字体的大小
let deg = random(-30, 30);//字体旋转角度
ctx.font = fs + "px Verdana"
ctx.fillStyle = rndCol();
ctx.textBaseline = "top";
// canvas.save()用来保存先前状态的
// canvas.restore()用来恢复之前保存的状态
// 注:两种方法必须搭配使用,否则没有效果
ctx.save();
ctx.translate(c_w / textArray.length * i + 15, random(15, c_h - 15));
ctx.rotate(deg * Math.PI / 180);
ctx.fillText(textArray[i], -15 + 5, -15);
ctx.restore();
}
}
drawText()
drawDot()
drawLine()
</script>
</html>