uniapp普通验证码

组件代码

<template>
	<view class="canvas-img-code" @click="clickCode">
		<canvas :style="{width:width+'px',height:height+'px'}" canvas-id="imgcanvas"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form:{
					check: '', //验证码
				},
				width: 120,
				height: 40,
			};
		},
		onReady() {
			let that = this;
			setTimeout(function() {
				that.initCode();
			}, 500)
		},
		onShow() {
			let that = this;
			setTimeout(function() {
				that.initCode();
			}, 500)
		},
		methods: {
			// 初始化验证码
			initCode() {
				console.log('start');
				var context = uni.createCanvasContext('imgcanvas', this),
					w = this.width,
					h = this.height;
				context.setFillStyle("white");
				context.setLineWidth(5);
				context.fillRect(0, 0, w, h);
				var pool = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "I", "M", "N", "O", "P", "Q",
						"R", "S",
						"T", "U", "V", "W", "S", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"
					],
					str = '';
				for (var i = 0; i < 4; i++) {
					var c = pool[this.rn(0, pool.length - 1)];
					var deg = this.rn(-30, 30);
					context.setFontSize(18);
					context.setTextBaseline("top");
					context.setFillStyle(this.rc(80, 150));
					context.save();
					context.translate(30 * i + 15, parseInt(h / 1.5));
					context.rotate(deg * Math.PI / 180);
					context.fillText(c, -15 + 5, -15);
					context.restore();
					str += c;
				}
				//生成的验证码在此写入缓存
				console.log('验证码:', str);
				uni.setStorage({
					key: 'imgcode',
					data: str,
				});
				for (var i = 0; i < 40; i++) {
					context.beginPath();
					context.arc(this.rn(0, w), this.rn(0, h), 1, 0, 2 * Math.PI);
					context.closePath();
					context.setFillStyle(this.rc(150, 200));
					context.fill();
				}
				context.draw();
				console.log('end');
			},
			rc(min, max) {
				var r = this.rn(min, max);
				var g = this.rn(min, max);
				var b = this.rn(min, max);
				return "rgb(" + r + "," + g + "," + b + ")";
			},
			rn(max, min) {
				return parseInt(Math.random() * (max - min)) + min;
			},

			//点击验证码,切换
			clickCode() {
				this.initCode();
			},
		}
	}
</script>

<style>
</style>

页面引用
在这里插入图片描述

以组件引用 import yzm from './components/zmszyzm.vue'

验证方式
this.zmyzm != '' && this.zmyzm.toLowerCase() == uni.getStorageSync('imgcode').toLowerCase()

获取本地缓存的验证码与输入的验证码做匹配 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值