Vue中自定义验证码

vue中利用canvas生成随机验证码

页面html代码:

此处引入了element-ui组件库

<div class="caCode">
 <el-input ref="tel" v-model="userInput" placeholder="请输入验证码"name="tel" type="text" tabindex="1" autocomplete="on" clearable />
 <canvas ref="canvas" @click="createCode" width="140" height="60"></canvas>
</div>

初始化调用:

this.createCode();

定义变量用来验证:

code: '', // 验证码字符串
userInput: '' // 用户输入的验证码

函数生成代码:

// 生成验证码
		createCode() {
			const that = this;
			let codeLength = 4; // 验证码长度
			let canvas = this.$refs.canvas;
			let ctx = canvas.getContext('2d');
			let codeChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			let code = '';
			for (let i = 0; i < codeLength; i++) {
				let charIndex = Math.floor(Math.random() * codeChars.length);
				code += codeChars.charAt(charIndex);
			}
			this.code = code;

			// 绘制验证码图片
			ctx.fillStyle = that.MathColor(180,230);
			ctx.fillRect(0, 0, canvas.width, canvas.height);
			ctx.font = that.MathNumber(30,40)+'px Arial';
			ctx.fillStyle = that.MathColor(80,180);
			ctx.fillText(code, 20, 45);
			for (var i = 0; i < 6; i++) {
				ctx.strokeStyle = that.MathColor(0, 255);
				ctx.beginPath();
				ctx.moveTo(that.MathNumber(0, canvas.width), that.MathNumber(0, canvas.height));
				ctx.lineTo(that.MathNumber(0, canvas.width), that.MathNumber(0, canvas.height));
				ctx.stroke();
			}
			for (var i = 0; i < 50; i++) {
				ctx.fillStyle = that.MathColor(0, 255);
				ctx.beginPath();
				ctx.arc(that.MathNumber(0, canvas.width), that.MathNumber(0, canvas.height), 0.5, 0, 2 * Math.PI);
				ctx.fill();
			}
		},
		//随机整数
		MathNumber(min, max) {
			var n = Math.floor(Math.random() * (max - min) + min);
			return n;
		},
		//随机颜色
		MathColor(min, max) {
			var r = this.MathNumber(min, max);
			var g = this.MathNumber(min, max);
			var b = this.MathNumber(min, max);
			return `rgb(${r},${g},${b})`;
		},

css:

.caCode {
	display: flex;
	height: 51px;
	border: 1px solid rgba(0, 0, 0, 0.1);
	border-radius: 5px;
	color: #333;
	margin-bottom: 22px;
	el-input {
		width: 60%;
	}
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值