验证码生成图片
- img的src会自动识别base64编码数据,直接用
import { ref, reactive } from "vue"
let nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];
let str = ref('');
let verVal
export const VerifyCode = (width: number, height: number) => {
function drawCode() {
const canvas = document.createElement('canvas') as HTMLCanvasElement
var context = canvas.getContext("2d");
context!.fillStyle = "cornflowerblue";
context!.fillRect(0, 0, width, height);
context!.fillStyle = "white";
context!.font = "25px Arial";
var rand = new Array();
var x = new Array();
var y = new Array();
for (var i = 0; i < 4; i++) {
rand[i] = nums[Math.floor(Math.random() * nums.length)]
x[i] = i * 20 + 10;
y[i] = Math.random() * 20 + 20;
context!.fillText(rand[i], x[i], y[i]);
}
str.value = rand.join('').toUpperCase();
for (var i = 0; i < 3; i++) {
drawline(canvas, context);
}
for (var i = 0; i < 30; i++) {
drawDot(canvas, context);
}
return reactive({
str,
url: canvas.toDataURL("image/png")
})
}
function drawline(_: any, context: any) {
context.moveTo(Math.floor(Math.random() * width), Math.floor(Math.random() * height));
context.lineTo(Math.floor(Math.random() * width), Math.floor(Math.random() * height));
context.lineWidth = Math.random();
context.strokeStyle = 'rgba(50,50,50,0.3)';
context.stroke();
}
function drawDot(_: any, context: any) {
var px = Math.floor(Math.random() * width);
var py = Math.floor(Math.random() * height);
context.moveTo(px, py);
context.lineTo(px + 1, py + 1);
context.lineWidth = 0.2;
context.stroke();
}
verVal = drawCode();
return verVal
}