画布实现随机验证码

1. html模板:

1 <div class="c-code">
2     <canvas id="c-cvs"></canvas>
3 </div>

2. 使用: 

  2.1 引用js文件

  2.2 在模板之外添加一个盒子,宽高必须给,验证码宽高与之相等
  2.3 每调用一次drawBg(),刷新一次
  2.4 drawBg().textArr 得到当前的文本内容存为数组
  2.5 drawBg().text 得到当前的文本内容存为字符串

3. js代码:

(function (w){
	var oCode=document.getElementsByClassName("c-code")[0];
	var cvs=document.getElementById("c-cvs");
	var ctx=cvs.getContext("2d");
	//设置整个内容宽高与父盒子相等
	oCode.style.width="100%";
	oCode.style.height="100%";
	
	function drawBg(){
		//获取盒子宽高
		this.width=oCode.offsetWidth;
		this.height=oCode.offsetHeight;
		//随机点坐标
		this.randomX=0;
		this.randomY=0;
		//存放验证码内容(数组)
		this.textArr=[];
		//存放验证码内容(字符串)
		this.text="";

		this._init();
		this.draw();
		this.addPoint();
		this.addText();
	}
	drawBg.prototype={
		constructor: drawBg,
		//设置画布宽高
		_init: function (){
			cvs.width=this.width;
			cvs.height=this.height;
		},
		//获取随机的颜色
		randomColor: function (){
			var colorStr="0123456789abcdef";
			var colorArr=colorStr.split("");
			this.color="#";
			//0-15随机数
			var randomNum;
			for (var i = 0; i < 6; i++) {
				randomNum=Math.floor(Math.random()*16)
				this.color+=colorArr[randomNum]
			}
			return this.color;
		},
		//绘制背景
		draw: function (){
			//每次创建先清除画布
			ctx.clearRect(0,0,this.width,this.height);
			ctx.fillStyle=this.randomColor();
			ctx.fillRect(0,0,this.width,this.height);
		},
		//绘制随机点
		randomPoint: function (){
			this.randomX=Math.random()*this.width;
			this.randomY=Math.random()*this.height;
			ctx.fillStyle=this.randomColor();
			ctx.fillRect(this.randomX,this.randomY,2,2);
			ctx.fill();
		},
		//添加多个随机点
		addPoint: function (){
			//生成的点的个数等于(宽*高/10)
			var num=Math.floor(this.width*this.height/10);
			for (var i = 0; i < num; i++) {
				this.randomPoint();
			}
		},
		//添加文本
		addText: function (){
			// 0-61随机数
			var randomNum;
			//textData: (0-9 a-z A-Z)
			var textData=[];
			for(var i=48;i<58;i++){
				textData.push(String.fromCharCode(i));
			}
			for(var i=65;i<91;i++){
				textData.push(String.fromCharCode(i));
			}
			for(var i=97;i<123;i++){
				textData.push(String.fromCharCode(i));
			}
			
			this.text="";
			this.textArr=[];
			for(var i=0;i<4;i++){
				randomNum=Math.floor(Math.random()*62);
				this.text+=textData[randomNum];
				this.textArr.push(textData[randomNum]);
			}
			//绘制文本
			ctx.font="bold 25px Arial";
			ctx.textAlign="center";
			ctx.textBaseline="middle";
			ctx.fillStyle=this.randomColor;
			ctx.fillText(this.text,this.width/2,this.height/2);
		}
	}

	w.drawBg=function (){
		return new drawBg();
	}
})(window)

 

4. 链接地址( http://hsianglee.top/component/randomCode.html )

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值