Canvas实现一个带干扰线条的随机数验证码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<canvas id="can" width="120" height="40" style="border: 1px solid #555555;">
		
		</canvas>
		<script>
			var can=document.getElementById("can");
			var con=can.getContext('2d');
			
			//随机生成从最小值到最大值的一组数字
			function rand(min,max) {
		        return Math.floor(Math.random()*(max-min))+min;
		    }
			//随机显示一根线条
	        function drawline(canvas, context) { 
	        		context.beginPath();
	                //起点与终点在canvas宽高内随机
	                context.moveTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height));  
	                context.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height));  
	                context.lineWidth = 1;	                
	                context.strokeStyle = '#275DB3';	       
	                context.stroke();  
	        }
	        linesum();
	        //循环显示多条线条
	        function linesum(){
	       		//每次调用该方法填充一次颜色覆盖之前的
       	 		con.fillStyle='white';
				//填充一个矩形 x,y坐标,x,y宽度
				con.fillRect(0,0,can.width,can.height);
		       	for (var i=0;i<20;i++) {
			       	drawline(can, con);
			    }
		    }
	        //验证码
	        function code(){
		       	var randnum=rand(1000,9999);				
				//居中
				con.textAlign = "center";
				con.font="25px 宋体";
				con.fillStyle="red";
				con.fillText(randnum,60,30);
	        }
	        code();
	        //点击触发函数
			can.onclick=function(){
				linesum();
				code();
			}
			
		</script>
	</body>
</html>

写的不是很好,大神可以提点我下,谢谢

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值