前端使用vue写随机图片验证码代码如下
<template>
<div class="captcha">
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
mounted() {
this.drawCaptcha();
},
methods: {
generateCode() {
const chars = [
"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",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];
let code = "";
for (let i = 0; i < 4; i++) {
const index = Math.floor(Math.random() * chars.length);
code += chars[index];
}
return code;
},
drawCaptcha() {
const code = this.generateCode();
const canvas = this.$refs.canvas;
const ctx = canvas.getContext("2d");
// 设置背景渐变
const grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "lightblue");
grd.addColorStop(1, "pink");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 170, 50);
// 设置字体样式
ctx.font = "25px Arial";
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
// 旋转文字
const angle = -(20 + Math.random() * 15);
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(angle * Math.PI / 180);
ctx.fillText(code, -code.length * 12, 5);
// 重置坐标系
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
}
};
</script>
<style>
.captcha {
margin: 20px;
}
canvas {
border: 1px solid #ccc;
border-radius: 5px;
}
</style>