效果
用法
引入js
import {createCode, drawCanvas} from '@/utils/verifyCode'
使用部分代码标签
<canvas
style="width: 200rpx;height: 60rpx;"
@click="getImgCode"
id="canvas"
canvas-id="canvas" >
</canvas>
使用部分代码js
getImgCode(){
this.ctx = uni.createCanvasContext('canvas', this);
this.code = createCode()
// canvas生成验证码
drawCanvas(this.ctx, this.code, 134, 55);
}
verifyCode.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()
}