js 随机生成验证码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .yzm{
      background-color: rgb(26, 224, 53);
      border-radius: 5px;
      cursor: pointer;
      display: block;
      margin: 100px auto;
    }
  </style>
</head>
<body>
  <!-- 画布标签,宽高在这里设定 -->
  <canvas class="yzm" width="110px" height="50px"></canvas>
  <script>
     window.addEventListener("DOMContentLoaded", function () {
      //  获取节点
      const yzm = document.querySelector(".yzm")
      // 画布绘制文字
      const cxt = yzm.getContext("2d");
      function showYzm() {
        // 每次生成新的随机码,都要清空上一次的随机码
        cxt.clearRect(0, 0, 150, 50); //清空画布区域
        // 随机码字符串
        let str = "012345678910ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 定义下边需要用到的变量
        let position = 0;
        let x, y;
        let fontSize = 30;
        // 开启路径
        cxt.beginPath();
        // 路径填充样式
        cxt.fillStyle = "#ccc";
        for (let i = 0; i < 4; i++) {
          x = 20 + (i * 20);//生成四个X坐标
          y = 25 + Math.floor(Math.random() * 20);//生成四个y坐标
          fontSize = 10 + Math.floor(Math.random() * 20);//字号
          cxt.font = "bold " + fontSize + "px Arial";//字体属性
          position = Math.floor(Math.random() * 35);//在36个字母和数字中随机生成一个索引值(运行了四次)
          cxt.fillText(str.substr(position, 1), x, y, 300);//通过substr截取4个str中的元素(position为随机变量所以截取数字随机)
        }
      }
      // 页面加载完成调用一次
      showYzm();
      // 每次点击再次调用
      yzm.addEventListener("click", function () {
        showYzm();
      });
    });

  </script>
</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值