vue后台系统登录需要使用到验证码验证功能
可以使用验证插件,如 vue2-verify、vue-puzzle-vcode、vue-monoplasty-slide-verify
Tips:现在大多数使用到的是接口返回图片
<canvas id="canvas" :width="canvas_width" :height="canvas_height" @click="showNumber"></canvas>
data (){
return {
code:"", // 数字验证码
canvas_width:"140",
canvas_height:"36"
}
}
// 获得验证码
showNumber(){
authCode().then((res)=>{
if(res.success){
this.code = res.data;
this.drawCode();
}
})
},
// 画数字
drawCode(){
let canvas = document.getElementById("canvas"); //获取到canvas的对象,演员
let context = canvas.getContext("2d"); //获取到canvas画图的环境,演员表演的舞台
console.log(context)
context.fillStyle = "#fff";
context.fillRect(0, 0, 300, 200);
for (let i = 0; i < this.code.length; i++) {
let deg = (Math.random() * 15 * Math.PI) / 180; //产生0~30之间的随机弧度
let x = 20 + i * 25; //文字在canvas上的x坐标
let y = 20 + Math.random() * 8; //文字在canvas上的y坐标
context.font = "bold 20px 微软雅黑";
context.translate(x, y);
context.rotate(deg);
context.fillStyle = this.randomColor();
context.fillText(this.code[i], 0, 0);
context.rotate(-deg);
context.translate(-x, -y);
}
for (let i = 0; i <= 5; i++) {
//验证码上显示线条
context.strokeStyle = this.randomColor();
context.beginPath();
context.moveTo(
Math.random() * this.canvas_width,
Math.random() * this.canvas_height
);
context.lineTo(
Math.random() * this.canvas_width,
Math.random() * this.canvas_height
);
context.stroke();
}
for (let i = 0; i <= 30; i++) {
//验证码上显示小点
context.strokeStyle = this.randomColor();
context.beginPath();
let x = Math.random() * this.canvas_width;
let y = Math.random() * this.canvas_height;
context.moveTo(x, y);
context.lineTo(x + 1, y + 1);
context.stroke();
}
},
/**
* @description:得到随机颜色
*/
randomColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")";
},