vue/js图形校验码验证
发布时间: 2023-11-08 15:22:40
作者: 王乐园 浏览次数:
1221
当前实例基于vue3+typescript的一个字母加数字的校验码,同理如果使用html只需要将ref转的id获取即可
图像模块 canvas
利用canvas绘图得到图片的效果
<template>
<canvas width="100" height="30" ref="CanvasRef" @click="handleDrawCode"></canvas>
</template>
canvas {
margin-left: 2rem;
vertical-align: middle;
/*vertical-align属性设置一个元素的垂直对齐。*/
box-sizing: border-box;
border: 1px solid #ddd;
cursor: pointer;
background-color: #eee;
}
随机颜色
/**得到随机的颜色值 */
const getColor = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")";
}
canvas画图
const CanvasRef = ref()
const state = reactive({
showCode: '',
})
onMounted(() => {
handleDrawCode()
})
/**生成并渲染出验证码图形 */
const handleDrawCode = () => {
state.showCode = ''
const canvas_width = CanvasRef.value.width;
const canvas_height = CanvasRef.value.height;
const canvas: any = CanvasRef.value;//获取canvas
const context = canvas.getContext("2d");//获取到canvas画图的环境
canvas.width = canvas_width;
canvas.height = canvas_height;
const sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,1,2,3,4,5,6,7,8,9,0";
const aCode = sCode.split(",");
const aLength = aCode.length;//获取到数组的长度
for (let i = 0; i < 4; i++) { //这里的for循环可以控制验证码位数
const j = Math.floor(Math.random() * aLength);//获取到随机的索引值
const deg = Math.random() - 0.5; //产生一个随机弧度
const txt = aCode[j];//得到随机的一个内容
state.showCode += txt.toLowerCase();//转小写
const x = 10 + i * 20;//文字在canvas上的x坐标
const y = 20 + Math.random() * 8;//文字在canvas上的y坐标
context.font = "bold 1.5rem 微软雅黑";
context.translate(x, y);
context.rotate(deg);
context.fillStyle = getColor();
context.fillText(txt, 0, 0);
context.rotate(-deg);
context.translate(-x, -y);
}
for (var i = 0; i <= 5; i++) { //验证码上显示线条
context.strokeStyle = getColor();
context.beginPath();
context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
context.stroke();
}
for (let i = 0; i <= 20; i++) { //验证码上的小点
context.strokeStyle = getColor();//随机生成
context.beginPath();
const x = Math.random() * canvas_width;
const y = Math.random() * canvas_height;
context.moveTo(x, y);
context.lineTo(x + 1, y + 1);
context.stroke();
}
}
验证
最后表单验证的时候一定把输入的内容转 小写
上一篇:(转载)追忆过往青春
下一篇:(转载)时光悠悠 岁月无言