700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 前端动态生成随机图形验证码

前端动态生成随机图形验证码

时间:2023-03-07 14:42:56

相关推荐

前端动态生成随机图形验证码

图形验证码示例图

<template><view class="dis-flex"><view style="margin-top: 8px;">验证码:</view><input:enableNative="false"style="width:100px;height:30px;border-bottom:1px solid #000;"v-model="verCode"name="verCode"id="verCode"><view @tap="refresh()" class="canvas-img-code">/*注: 这里 是支付宝小程序,用的是id,其他平台是用canvas-id='' */<canvas :style="{width:width+'px',height:height+'px'}" id="imgcanvas" @error="canvasIdErrorCallback"></canvas></view></view></template><script>data() {return {verCode: '', // 验证码,width: 120,height: 45,}},onShow() {const that = this;setTimeout(() => {that.init();}, 1000);},methods: {// 初始化验证码init() {console.log('start');const context = uni.createCanvasContext('imgcanvas', this);const w = this.width;const h = this.height;context.setFillStyle('white');context.setLineWidth(5);context.fillRect(0, 0, w, h);const 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'];let str = '';for (let i = 0; i < 4; i++) {const c = pool[this.rn(0, pool.length - 1)];const 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 (let 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) {const r = this.rn(min, max);const g = this.rn(min, max);const b = this.rn(min, max);return `rgb(${r},${g},${b})`;},rn(max, min) {return parseInt(Math.random() * (max - min)) + min;},refresh() {this.init();},canvasIdErrorCallback(e) {console.error(e.detail.errMsg);},}</script>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。