【JS】滑动验证实现
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
以下是一个简单的滑动验证实现示例,使用了HTML5的<canvas>
元素来绘制验证图片,并用JavaScript来处理验证逻辑。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滑动验证示例</title>
<style>
#captcha {
width: 300px;
height: 100px;
border: 1px solid #ccc;
margin: 20px 0;
position: relative;
cursor: pointer;
}
#captchaCanvas {
position: absolute;
top: 0;
left: 0;
}
#refresh {
position: absolute;
top: 40px;
right: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="captcha">
<canvas id="captchaCanvas"></canvas>
<span id="refresh">刷新</span>
</div>
<script>
const captcha = document.getElementById('captcha');
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
let offset = 0;
// 生成验证码
function generateCaptcha() {
let code = '';
const codeLength = 4; // 验证码长度
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
for (let i = 0; i < codeLength; i++) {
code += random(0, 9); // 生成随机数字
}
return code;
}
// 绘制背景噪声线条
function drawNoise() {
for (let i = 0; i < 5; i++) {
ctx.beginPath();
ctx.moveTo(random(0, 300), random(0, 100));
ctx.lineTo(random(0, 300), random(0, 100));
ctx.strokeStyle = randomColor();
ctx.stroke();
}
}
// 生成随机颜色
function randomColor() {
return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;
}
// 初始化验证码
function init() {
const code = generateCaptcha();
canvas.width = 300;
canvas.height = 100;
ctx.font = '40px Arial';
ctx.fillStyle = randomColor();
ctx.fillText(code, 20, 50);
drawNoise();
captcha.addEventListener('mousedown', (e) => {
offset = e.clientX - captcha.offsetLeft;
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', up);
});
}
// 拖动时更新位置
function move(e) {
if (captcha.offsetLeft + captcha.offsetWidth - e.clientX <= 0) {
captcha.style.left = e.clientX - offset + 'px';
}
}
// 拖动结束
function up() {
document.removeEventListener(
评论已关闭