【uniapp】Canvas draws verification code

Canvas draws verification code

uniapp uses canvas to draw the verification code. The main code is as follows:

Source: dcloud plug-in market canvas drawing verification code picture


<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>

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42216995/article/details/130933620