【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图形校验码验证 - 简书 来写,原文直接放来我的项目里有些问题,做了一些改动,作为学习笔记供有需要的人参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值