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)
 }

猜你喜欢

转载自blog.csdn.net/puhuihui/article/details/128565679
今日推荐