- 創(chuàng)建生成驗證碼文件 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()
}
- 相關頁面引用
2.1頁面部分
<canvas
id="canvas"
canvas-id="canvas" >
</canvas>
js部分
// 引用
import {createCode, drawCanvas} from '@/utils/verifyCode.js';
// 畫布上下文
this.ctx = uni.createCanvasContext('canvas', this);
this.code = createCode()
// canvas生成驗證碼
drawCanvas(this.ctx, this.code, 134, 55);