<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="120" height="40" onclick="draw()"></canvas>
<script>
let pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
function randomColor(min, max) {
const r = randomNum(min, max)
const g = randomNum(min, max)
const b = randomNum(min, max)
return `rgb(${r},${g},${b})`
}
function draw() {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
// 填充色 随机
ctx.fillStyle = randomColor(100, 230)
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 随机生成字符串
let imgCode = ''
for (let i = 0; i < 4; i++) {
const text = pool[randomNum(0, pool.length)]
imgCode += text
// 随机字体大小
const fontSize = randomNum(18, 40)
// 随机旋转角度
const deg = randomNum(-30, 30)
ctx.font = `${fontSize}px Simhei`
ctx.textBaseline = 'top'
ctx.fillStyle = randomColor(80, 150)
ctx.save() // 将当前状态封存入栈
ctx.translate(30 * i + 15, 15)
ctx.rotate((deg * Math.PI) / 180)
ctx.fillText(text, -10, -15)
ctx.restore() //
}
// 随机生成干扰线条
for (let i = 0; i < 5; i++) {
ctx.beginPath()
ctx.moveTo(randomNum(0, canvas.width), randomNum(0, canvas.height))
ctx.lineTo(randomNum(0, canvas.width), randomNum(0, canvas.height))
ctx.strokeStyle = randomColor(120,230)
ctx.closePath()
ctx.stroke()
}
// 随机小点
for(let i = 0; i < 40; i++){
ctx.beginPath()
ctx.arc(randomNum(0,canvas.width),randomNum(0,canvas.height),1,0,2 * Math.PI)
ctx.fillStyle = randomColor(150,200)
ctx.closePath()
ctx.fill()
}
}
draw()
</script>
</body>
</html>