uniapp使用画布生成验证码

本文介绍如何在uni-app中利用JavaScript操作画布来创建验证码。通过在HTML中设置画布元素,并在JS中进行画布初始化和延迟显示,确保了验证码的生成效果。文章还提供了封装好的JS文件供参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html:

<canvas
   style="width: 200rpx;height: 60rpx;"
   @click="refreshCaptcha"
   id="canvas"
   canvas-id="canvas" >
</canvas>

js: 画布初始化显示延迟一下。

// 引入封装的验证码文件
import {createCode, drawCanvas} from '@/util/verifyCode.js';

 onShow(){
// 画布上下文
    setTimeout(()=>{
      this.init();
    }, 100)
  },
    methods: {
	    init(){
	      this.ctx = uni.createCanvasContext('canvas', this);
	      this.code = createCode()
	      // canvas生成验证码
	      drawCanvas(this.ctx, this.code, 134, 55);
	    },
	      refreshCaptcha(){
		      this.init();
		    },
    }

下面是封装的 js文件

/** 获取四位随机码
 * @return  string
 */
export function createCode(){
    var str = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
    let codeText = ''
    for(let i = 1; i <= 4; i++){
        let index = Math.floor(Math.random() * 62 )
        let code = str.charAt(index)
        codeText += code
    }
    return codeText;
}

/**
 *  @desc   随机颜色
 *  @return     string
 */
function randomColor() {
    var colorValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
    var colorArray = colorValue.split(",");
    var color = "#";
    for (var i = 0; i < 6; i++) {
        color += colorArray[Math.floor(Math.random() * 16)];
    }
    return color;
}
/**
 *  @desc   干扰线是就是在画布上在随机的位置上生成随机长度的线
 *  @return     string
 */
function randomLine(ctx, canWidth, canHeight){
    for(let i =0; i< 8; i++){   //绘制条线
        ctx.beginPath();
        ctx.moveTo(Math.floor(Math.random() * canWidth), Math.floor(Math.random() * canHeight));    //绘制线的初始位置
        ctx.lineTo(Math.floor(Math.random() * canWidth), Math.floor(Math.random() * canHeight));    //绘制线的末位置
        ctx.setStrokeStyle(randomColor());  //设置线的颜色
        ctx.stroke();   //绘制
    }
}
/**
 *  @desc   随机字符位置。
 *  @return string
 */
function randomCode(ctx, str){
    for (let i = 0; i < 4; i++) {
        ctx.setFontSize(28 + Math.floor(Math.random() * 4 - 2));
        ctx.fillText(str[i], 20 * i + 10, 24);
        ctx.setFillStyle(randomColor());
    }
}

/**
 *  @desc   画线和字符
 *  @return string
 */
export function drawCanvas(ctx, str, canWidth, canHeight){
    randomCode(ctx, str)
    randomLine(ctx, canWidth, canHeight)
    ctx.draw()
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值