欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 【HTML】纯前台字符验证码

【HTML】纯前台字符验证码

2025/11/28 9:32:21 来源:https://blog.csdn.net/BigBigHang/article/details/141133505  浏览:    关键词:【HTML】纯前台字符验证码

效果图:

大致思路:

1.在<canvas>画布里写出几个字符;

2.给字符一个随机的角度和颜色;

3.给字符上画出一些干扰线和干扰点。


<canvas width="100" height="30" id="canvasRef" @click="handleDrawCode"></canvas>
      /** 生成并渲染出验证码图形 */handleDrawCode () {const CanvasRef = document.getElementById('canvasRef');this.showCode = '';const canvasWidth = CanvasRef.width;const canvasHeight = CanvasRef.height;const context = CanvasRef.getContext('2d'); // 获取到canvas画图的环境context.clearRect(0, 0, canvasWidth, canvasHeight);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; // 获取到数组的长度// 这里获取4位验证码for (let i = 0; i < 4; i++) { const j = Math.floor(Math.random() * aLength); // 获取到随机的索引值const deg = Math.random() - 0.5; // 产生一个随机弧度const txt = aCode[j]; // 得到随机的一个内容this.showCode += txt.toLowerCase(); // 转小写const x = 10 + i * 20; // 文字在canvas上的x坐标const y = 20 + Math.random() * 8; // 文字在canvas上的y坐标context.font = '0.5rem 微软雅黑';context.translate(x, y);context.rotate(deg);context.fillStyle = this.getColor();context.fillText(txt, 0, 0);context.rotate(-deg);context.translate(-x, -y);}// 验证码上显示5根线条for (let i = 0; i <= 5; i++) { context.strokeStyle = this.getColor();context.beginPath();context.moveTo(Math.random() * canvasWidth, Math.random() * canvasHeight);context.lineTo(Math.random() * canvasWidth, Math.random() * canvasHeight);context.stroke();}// 验证码上添加20个小点for (let i = 0; i <= 20; i++) { context.strokeStyle = this.getColor(); // 随机生成context.beginPath();const x = Math.random() * canvasWidth;const y = Math.random() * canvasHeight;context.moveTo(x, y);context.lineTo(x + 1, y + 1);context.stroke();}},/** 得到随机的颜色值 */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 {margin-left: 2rem;vertical-align: middle;/*vertical-align属性设置一个元素的垂直对齐。*/box-sizing: border-box;border: 1px solid #ddd;cursor: pointer;background-color: #eee;}

本文参考 vue/js图形校验码验证 - 简书 来写,原文直接放来我的项目里有些问题,做了一些改动,作为学习笔记供有需要的人参考。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词