【uniapp】canvas 绘制验证码

canvas 绘制验证码

uniapp 用canvas 绘制验证码,主要代码如下:

来源:dcloud插件市场 canvas 绘制验证码图片


<template>
	<view>
		<view class="home-box">
			<canvas canvas-id="captcha" :style="{ width: canvasW + 'px', height: canvasH + 'px' }"></canvas>
			<view class="" @click="getDrawCanvas">刷新</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			canvasW: 120, //canvas宽度
			canvasH: 50 //canvas高度
		};
	},
	mounted() {
		this.getDrawCanvas();
	},
	methods: {
		// 开始绘制
		getDrawCanvas() {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			const ctx = uni.createCanvasContext('captcha', this);
			// 画背景
			ctx.fillStyle = '#f2f2f2';
			ctx.fillRect(0, 0, this.canvasW, this.canvasH);
			// 画混淆线条
			for (let i = 0; i < 5; i++) {
				ctx.beginPath();
				ctx.strokeStyle = this.getRandomColor();
				ctx.moveTo(Math.random() * this.canvasW, Math.random() * this.canvasH);
				ctx.lineTo(Math.random() * this.canvasW, Math.random() * this.canvasH);
				ctx.stroke();
			}
			// 画验证码
			const code = this.getRandomCode();
			ctx.font = 'bold 24px sans-serif';
			ctx.textBaseline = 'middle';
			for (let i = 0; i < code.length; i++) {
				ctx.fillStyle = this.getRandomColor();
				ctx.fillText(code[i], 20 * i + Math.random() * 10, 30 + Math.random() * 10);
			}
			ctx.draw();
			uni.hideLoading();
		},
		getRandomCode() {
			const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			let code = '';
			for (let i = 0; i < 4; i++) {
				code += chars.charAt(Math.floor(Math.random() * chars.length));
			}

			return code;
		},
		getRandomColor() {
			return `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
		}
	}
};
</script>

<style lang="scss">
.home-box {
	display: flex;
	align-items: center;
	justify-content: center;
	view {
		margin-left: 10rpx;
		font-size: 28rpx;
	}
}
</style>

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值