canvas验证码制作

<canvas id="canvas" width="120" height="40"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
draw();
canvas.onclick = function () {
context.clearRect(0, 0, 120, 40); //清除画布
draw();
}
function getColor() {
// 0 - 255之间的随机数
var r = Math.round(Math.random() * 255);
var g = Math.round(Math.random() * 255);
var b = Math.round(Math.random() * 255);
return `rgb(${r},${g},${b})`;
// return "rgb(" + r + "," + g + "," + b + ")";
}
function draw() {
context.strokeRect(0, 0, 120, 40); //绘制一个描边矩形
 
//随机绘制8条直线, 起始坐标 在矩形任何区域, 结束坐标在矩形任何区域
for (var i = 0; i < 8; i++) {
context.beginPath();
context.moveTo(Math.random() * 120, Math.random() * 40);
context.lineTo(Math.random() * 120, Math.random() * 40);
context.strokeStyle=getColor();
context.stroke();
}
//20个小点, 颜色随机
for (var i = 0; i < 20; i++) {
context.beginPath();
var x = Math.random() * 120;
var y = Math.random() * 40;
context.arc(x,y,1,0,360 * (Math.PI/180));
context.fillStyle=getColor();
context.fill();
}

var aCode = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (var i = 0; i < 4; i++) {
context.save();
var x = 20 + i * 20; //每个文字间隔是 20个像素
var y = 20 + 10 * Math.random(); //垂直坐标是 20 - 30个像素之间

var index = Math.floor(Math.random() * aCode.length);//随机索引值
var txt = aCode[index];
context.font = "bold 25px 微软雅黑";
context.fillStyle=getColor();
//水平和垂直方向的位移
context.translate(x,y);
//对文字的旋转
var deg=90*Math.random()* (Math.PI/180);
context.rotate(deg);
//写入文字
context.fillText(txt, 0, 0);
context.restore();
 
}
}
posted @ 2021-01-31 14:57  lanyan  阅读(84)  评论(0编辑  收藏  举报