<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
canvas {
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="100" height="40">
您的浏览器不支持canvas
</canvas>
</body>
<script type="text/javascript">
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
//随机字符(透明度)(大小随机,位置随机);
var strStore = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//随机函数
function roundNum(min, max) {
return parseInt(Math.random() * (max - min) + min);
}
//文字内容部分:
var str = "";
for(var i = 0; i < 5; i++) {
context.beginPath();
//随机颜色(浅色:RGB - 200~250)
var color = `rgb(${roundNum(0,255)},${roundNum(0,255)},${roundNum(0,255)})`;
context.fillStyle = color;
context.font = roundNum(20,30)+"px Arial";
context.textAlign = "center";
str = strStore[roundNum(0,strStore.length)];
context.fillText(str, 10 + 18 * i, roundNum(20,35));
}
//10个左右的随机(长度随机,位置随机),干扰线
for(var j = 0; j < roundNum(5, 10); j++) {
context.beginPath();
var color = `rgb(${roundNum(0,255)},${roundNum(0,255)},${roundNum(0,255)})`;
context.strokeStyle = color;
context.moveTo(roundNum(0, 100), roundNum(0, 40));
context.lineTo(roundNum(0, 100), roundNum(0, 40));
context.stroke();
}
//干扰项:10个左右的随机(半径随机,位置随机),干扰圆
for(var j = 0; j < roundNum(5, 10); j++) {
context.beginPath();
context.fillStyle = color;
context.arc(roundNum(0, 100), roundNum(0, 40), roundNum(0, 5), Math.PI * 2 / (roundNum(1, 360)), Math.PI * 2 / (roundNum(1, 360)));
context.fill();
}
</script>
</html>