js 随机验证码(已封装,复制即用)

该验证码函数的功能:

  1. 忽略大小写
  2. 点击图刷新验证码
  3. 返回图中验证码值,便于校验验证码

在这里插入图片描述

html

 <canvas class="verify" style=" width: 120px; height: 40px; " @click="handleDraw" ></canvas>

js

	// 调用验证码函数 只需要传递  dom参数,该函数返回dom验证码的值用作校验验证码
	
	// 随机数
	 const randomNum = (min, max) => {
	   return parseInt(Math.random() * (max - min) + min)
	 }
	 // 验证码数组
	 var sjyzm = []
	 // 用于最后验证的验证码
	 let yzYZM = ''

	 // 随机颜色
	 const randomColor = (min, max) => {
	   const r = randomNum(min, max)
	   const g = randomNum(min, max)
	   const b = randomNum(min, max)
	   return `rgb(${r},${g},${b})`
	 }
	 let state={
		  pool:'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz',
		  width: 120, // canvas宽
		  height: 40
	 }

export	function verification(dom){
		const ctx = dom.getContext('2d')
		  ctx.fillStyle = "rgb(255,255,255)"
		  // 填充的位置
		  ctx.fillRect(0, 0, 120, 40)
		  
		  // 随机产生字符串,并且随机旋转
		  for (let i = 0; i < 4; i++) {
		    // 随机的一个字符
		    const text = state.pool[randomNum(0, state.pool.length)]
		    sjyzm[i] = text

		
		    // 随机的字体大小
		    const fontSize = randomNum(18, 40)
		    // 字体随机的旋转角度
		    const deg = randomNum(-30, 30)
		    ctx.font = fontSize + 'px Simhei'
		    ctx.textBaseline = 'top'
		    ctx.fillStyle = randomColor(80, 150)
		    ctx.save()
		    ctx.translate(30 * i + 15, 15)
		    ctx.rotate((deg * Math.PI) / 180)
		    ctx.fillText(text, -15 + 5, -15)
		    ctx.restore()
		  }
		  getYZM()
		  return yzYZM
	}
	const getYZM = () =>{
	  let yzYZMs = '' // 用于最后验证的验证码
	  sjyzm.forEach(function(item){
	    item = item.toLowerCase()
	    yzYZMs =yzYZMs+item
	  })
	  yzYZM = yzYZMs
	}

使用

// 接收图中验证码值的变量
var code;
onMounted(()=>{
		 code=  verification(document.querySelector('canvas'))
		 console.log("验证码************",code)
	 })
// 点击图片重新绘制验证码
const handleDraw = () => {
   code=  verification(document.querySelector('canvas'))
   console.log("验证码************",code)
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值