math的random用法(生成随机数字验证码)

本文介绍了如何利用math的random方法来生成随机数字验证码,讲解了具体步骤和实现方式,适用于验证码的生成和安全验证场景。
摘要由CSDN通过智能技术生成
    //生成1位随机数字
    System.out.println((int)((Math.random()*9+1)));
    
    //生成2位随机数字
    System.out.println((int)((Math.random()*9+
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用 Canvas 绘制随机数验证码的示例代码: ```html <canvas id="captcha" width="120" height="40"></canvas> <button onclick="refresh()">刷新验证码</button> ``` ```javascript const canvas = document.getElementById('captcha'); const ctx = canvas.getContext('2d'); function refresh() { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 绘制背景 ctx.fillStyle = '#f2f2f2'; ctx.fillRect(0, 0, canvas.width, canvas.height); // 绘制随机数 const code = Math.random().toString().slice(2, 6); ctx.font = 'bold 30px Arial'; ctx.fillStyle = '#333'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(code, canvas.width / 2, canvas.height / 2); // 绘制干扰线 for (let i = 0; i < 4; i++) { ctx.beginPath(); ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height); ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height); ctx.strokeStyle = '#ddd'; ctx.stroke(); } } // 初始化验证码 refresh(); ``` 代码中,我们首先获取了 Canvas 对象和 2D 上下文对象 ctx,然后定义了一个 refresh 函数来生成并绘制随机数验证码。 在 refresh 函数中,我们首先使用 clearRect 方法清空画布,并使用 fillRect 方法绘制灰色背景。接着,我们使用 Math.random 方法生成一个 4 位的随机数,使用 fillText 方法将其绘制在画布中央。最后,我们使用 beginPath、moveTo、lineTo、strokeStyle 和 stroke 方法来绘制 4 条随机颜色的干扰线。 最后,我们在 HTML 中添加一个按钮,并设置其 onclick 事件为 refresh 函数,以便用户可以通过点击按钮来刷新验证码
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值