图形验证码 前端生成

话不多说,直接上源码,内部有注释,字体旋转地方会比较复杂,在下方有图像解释

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" width="120px" height="40px"></canvas>
  <script>
    let canvas = document.getElementById('canvas');
    let context = canvas.getContext('2d');
    draw();
    //绘制图形
    function draw() {
      //每次绘画前,清空画板
      context.clearRect(0, 0, 120, 40);
      //顶个边框
      context.strokeRect(0, 0, 120, 40);
      //设置随机数选项
      let aCode = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g'];
      //画出随机数
      for (let i = 0; i < 4; i++) {
        let x = 20 + 20 * i;
        let y = 20 + 10 * Math.random();
        let index = Math.floor(Math.random() * aCode.length);
        let txt = aCode[index];
        context.font = 'bold 20px 微软雅黑';
        context.fillStyle = getColor();
        //从此步开始,为字母旋转
        context.translate(x, y);
        let deg = Math.random() * 70 * Math.PI / 180;
        context.rotate(deg);
        context.fillText(txt, 0, 0);
        context.rotate(-deg);
        context.translate(-x, -y);
      }
      //设置干扰线 8条
      for (let i = 0; i < 8; i++) {
        context.beginPath();
        context.moveTo(Math.random() * 120, Math.random() * 40);
        context.lineTo(Math.random() * 120, Math.random() * 40);
        context.strokeStyle = getColor();
        context.stroke();
      }
      //设置干扰点 20 个
      for (let i = 0; i < 20; i++) {
        context.beginPath();
        let x = Math.random() * 120;
        let y = Math.random() * 40;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.strokeStyle = getColor();
        context.stroke();
      }
    }
    //获取随机颜色
    function getColor() {
      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})`
    }
    //点击刷新
    canvas.onclick = function () {
      draw();
    }
  </script>
</body>

</html>

复制上面的代码即可实现前端验证码的生成,字体旋转原理如下图:

1、首先执行步骤一,将画布移动至目标字体位置,然后进行旋转(注意:旋转为弧度,不为角度)

2、旋转完成后,写入文字,此时写入文字应在旋转完成后的左上角

3、然后执行步骤二,将画布还原至原来的位置

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值