<!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},$)`
}
function draw() {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
// 填充色 隨機(jī)
ctx.fillStyle = randomColor(100, 230)
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 隨機(jī)生成字符串
let imgCode = ''
for (let i = 0; i < 4; i++) {
const text = pool[randomNum(0, pool.length)]
imgCode += text
// 隨機(jī)字體大小
const fontSize = randomNum(18, 40)
// 隨機(jī)旋轉(zhuǎn)角度
const deg = randomNum(-30, 30)
ctx.font = `${fontSize}px Simhei`
ctx.textBaseline = 'top'
ctx.fillStyle = randomColor(80, 150)
ctx.save() // 將當(dāng)前狀態(tài)封存入棧
ctx.translate(30 * i + 15, 15)
ctx.rotate((deg * Math.PI) / 180)
ctx.fillText(text, -10, -15)
ctx.restore() //
}
// 隨機(jī)生成干擾線條
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()
}
// 隨機(jī)小點(diǎn)
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>