前端验证码如何制作
本质上就是canvas,倘若你还不会canvas,那么就去MDN搜一下,学一学2d下的API,就能使用了
直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas class="canvas" width="200" height="60"></canvas>
<script>
const drawing = document.querySelector('.canvas')
const context = drawing.getContext("2d")
init([1, 2, 3, 4])
drawing.addEventListener('click', () => {
let arr = []
for (let i = 0; i < 4; i++) {
arr.push(Math.floor(Math.random() * 10))
}
console.log(arr)
init(arr)
})
function init(arr) {
// // 填充颜色
context.fillStyle = "lightblue"
// // 绘制一个填充的矩形
context.fillRect(0, 0, 500, 500)
// // 绘制一个描边的矩形
// context.strokeRect(30, 30, 50, 50)
context.strokeStyle = 'black'
context.strokeRect(0, 0, 200, 60)
drawLine(context)
drawPoint(context)
drawCharacter(context, arr)
}
// 绘制干扰线
function drawLine(ctx) {
for (let i = 1; i <= 10; i++) {
let x = Math.round(Math.random() * 255)
let y = Math.round(Math.random() * 255)
let z = Math.round(Math.random() * 255)
ctx.fillStyle = `rgb(${x},${y},${z})`
ctx.beginPath()
let y1 = Math.round(Math.random() * 40)
let x1 = Math.round(Math.random() * 200)
let y2 = Math.round(Math.random() * 40)
let x2 = Math.round(Math.random() * 200)
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.fill()
}
}
// 绘制圆点
function drawPoint(ctx) {
for (let i = 1; i <= 100; i++) {
let x = Math.round(Math.random() * 255)
let y = Math.round(Math.random() * 255)
let z = Math.round(Math.random() * 255)
ctx.fillStyle = `rgb(${x},${y},${z})`
ctx.beginPath()
let y1 = Math.round(Math.random() * 40)
let x1 = Math.round(Math.random() * 200)
ctx.arc(x1, y1, 1, 0, 2 * Math.PI, false)
ctx.fill()
}
}
// 绘制字体
function drawCharacter(ctx, fonts) {
let i = 0
for (let i = 0; i < fonts.length; i++) {
let x = Math.round(Math.random() * 255)
let y = Math.round(Math.random() * 255)
let z = Math.round(Math.random() * 255)
ctx.fillStyle = `rgb(${x},${y},${z})`
ctx.font = 'bold 45px Arial'
ctx.textBaseline = 'baseline'
ctx.fillText(fonts[i], 50 + i * 30, 40)
}
}
</script>
</body>
</html>