利用canvas来绘制一个图形验证码
话不多说,直接贴代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图形验证码</title>
</head>
<body>
<canvas id="code" width="120" height="40"></canvas>
</body>
<script>
function colorRandom(){
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
return "rgb("+ r + ","+ g +","+ b+")";
}
function getRandomNum(min,max){
return Math.floor(Math.random()*(max-min)+min);
}
function getCode(){
canvas = document.getElementById("code");
context = canvas.getContext('2d');
context.fillStyle = colorRandom();//显示验证码区域的背景色
var width = canvas.width;
var height = canvas.height;
context.rect(0,0,width,height);
context.fill();
for(var i = 0;i<4;i++){
context.font = getRandomNum(25,30) + 'px 微软雅黑' //数字随机大小
context.fillStyle = colorRandom(); //数字颜色
var tempNum = getRandomNum(0,9); //0-9的随机数
var posX = i * 25 + 10; //随机x轴方向绘制的坐标值
var posY = getRandomNum(25,35); //随机y轴方向绘制的坐标值
var deg = getRandomNum(-45,45); //随机旋转在-30到30度之间
context.translate(posX,posY); //移动到绘制位置
context.rotate(deg * Math.PI/180); //旋转角度
context.fillText(tempNum,0,0); //绘制
context.rotate(-deg * Math.PI/180); //还原旋转角度
context.translate(-posX,-posY); //还原到移动前的位置
}
//绘制干扰线
for(var i=0; i<4; i++){
context.strokeStyle = colorRandom();
context.beginPath();
context.moveTo(Math.random() * width, Math.random() * height);
context.lineTo(Math.random() * width, Math.random() * height);
context.stroke();
}
//绘制干扰点
for(var i=0; i<100; i++){
context.fillStyle = colorRandom(0,255);
context.beginPath();
context.arc(getRandomNum(0,width),getRandomNum(0,height), 1, 0, 2*Math.PI);
context.fill();
}
}
getCode()
</script>
</html>