前端实现图片验证码效果(数字和字母)

1.verification-code.js

;(function(){
var data = [];//验证码数据
function picVerificationCode(config){
	/*
	验证码:数字和字母组成
	@param config {Object} 配置参数
	@param config.container {DOM元素} 验证码显示容器 必填
	@param config.num {Number} 验证码个数 非必填
	@param config.iconum {Number} 背景斑点个数 非必填
	@param config.changeBtn {DOM元素数组} 点击刷新验证码 非必填
	@param config.strFontSize {Array} 验证码字符大小 非必填
	@param config.width {Number} 验证码显示容器宽度 非必填
	@param config.height {Number} 验证码显示容器高度 非必填
	@param config.background {String} 验证码显示容器背景颜色 非必填
	@param config.cimgRefresh {Boolean} 是否点击验证码图片后刷新验证码 非必填
	*/
	//参数判断
	if(dataType(config)!='Object'){
		console.log('参数必须是object')
		return
	}
	if(!config.container||!isElement(config.container)){
		console.log('container参数必须是Dom元素')
		return;
	}
	//参数初始化(默认值)
	var defalutConfig = {
		num:4,
		iconum:10,
		width:160,
		height:40,
		background:'#ddd',
		fsize:[18,20,22,16],
		cimgRefresh:true
	}
	var config = Object.assign({},defalutConfig,config);//合并参数
	var verificationCode=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'];
	var tlist = [],//验证码字符数组
	color=[],//字符颜色
	rote=[],//字符旋转角度
	fsize=[];//字符字体大小
	config.container.innerHTML = '';//初始化验证码容器
	for(var i = 0;i<config.num;i++){
		var a = '';
		for(var j=0;j<3;j++){
			a+=randomNum(255).toString(16)
		}
		if(a.length == 4||a.length == 5){
			a = a.substr(0,3)
		}
		color.push('#'+a)
		if(config.fsize[i]){
			fsize.push(config.fsize[i]+'px')
		}else{
			fsize.push(config.fsize[randomNum(0,config.fsize.length-1)]+'px')	
		}
		tlist.push(verificationCode[randomNum(61)]);
		rote.push(randomNum(-45,45));
	}
	//设置验证码容器样式
	var box = config.container
	box.style.background = config.background;
	box.style.width = config.width+'px';
	box.style.height = config.height+'px';
	box.style.lineHeight = config.height+'px';
	box.style.display = 'inline-block';
	box.style.position = 'relative';
	box.style.textAlign = 'center';
	box.style.padding = 0;
	box.style.userSelect = 'none';
	var boxWidth = box.offsetWidth;
	var boxHeight = box.offsetHeight;

	var IconColor=[];//斑点颜色
	for(var m=0;m<config.iconum;m++){
		var threeColor = '';
		for(var j=0;j<3;j++){
			threeColor +=randomNum(255).toString(16)
		}
		if(threeColor.length == 4||threeColor.length == 5){
			threeColor = threeColor.substr(0,3)
		}
		IconColor.push('#'+threeColor)
	}
	for(var n=0;n<config.iconum;n++){
		var eltag = document.createElement("div");
		eltag.style.background = IconColor[n];
		eltag.style.position = 'absolute';
		eltag.style.width = '3px';
		eltag.style.height = '3px';
		eltag.style.borderRadius = '50%';
		eltag.style.top = randomNum(boxHeight-2)+'px';
		eltag.style.left = randomNum(boxWidth-2)+'px'
		box.appendChild(eltag)//添加斑点
	}
	for(var k=0;k<config.num;k++){
		//添加验证码字符
		var span = document.createElement("span");
		span.innerHTML=tlist[k];//内容
		span.style.color=color[k];//颜色
		span.style.fontSize=fsize[k];//字体大小
		span.style.display = 'inline-block';
		span.style.width = Math.floor((config.width/config.num))+'px';
		if(supportCss3('transform')){
			//浏览器如果支持css3 transform则设置
			span.style.transform='rotate('+rote[k]+'deg)';//旋转角度
		}
		box.appendChild(span)
	}
	//点击刷新验证码
	if(config.cimgRefresh){
		config.container.addEventListener('click',function(){
			picVerificationCode(Object.assign({},config,{cimgRefresh:false,changeBtn:null}))
		},true)
	}
	if(dataType(config.changeBtn)=='Array'){
		config.changeBtn.forEach(function(item,index){
			if(!isElement(item))return;
			item.addEventListener('click',function(){
				picVerificationCode(Object.assign({},config,{cimgRefresh:false,changeBtn:null}))
			},true)
		})
	}
	config.container.setAttribute('data-verificode',tlist)
	data = tlist;
	return tlist;
}
/******获取验证码数据******/
function getData(){
	return data
}
/******数组乱序******/
function shuffle(arr) {
  var length = arr.length,
    randomIndex,
    temp;
  while (length) {
    randomIndex = Math.floor(Math.random() * (length--));
    temp = arr[randomIndex];
    arr[randomIndex] = arr[length];
    arr[length] = temp
  }
  return arr;
}
/******判断浏览器是否支持某个css属性*******/
function supportCss3(style) {
    var prefix = ['webkit', 'Moz', 'ms', 'o'],
        i,
        humpString = [],
        htmlStyle = document.documentElement.style,
        _toHumb = function (string) {
            return string.replace(/-(\w)/g, function ($0, $1) {
                return $1.toUpperCase();
            });
        };

    for (i in prefix)
        humpString.push(_toHumb(prefix[i] + '-' + style));

    humpString.push(_toHumb(style));

    for (i in humpString)
        if (humpString[i] in htmlStyle) return true;

    return false;
}
/******判断js变量是否是DOM元素*******/
function isElement(OBJ){
	return HTMLElement?OBJ instanceof HTMLElement:(OBJ && typeof OBJ === 'object' &&(OBJ.nodeType === 1||OBJ.nodeType === 9) && typeof OBJ.nodeName === 'string')
}
/******判断数据类型*******/
function dataType(data){
	if(data === null) return 'Null';
	if(data === undefined) return 'Undefined';
	return Object.prototype.toString.call(data).slice(8,-1);

}
/******获取[a,b]范围内的随机数******/
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
}
window.verifiCode = {
	picVerificationCode:picVerificationCode,
	getData:getData,
	shuffle:shuffle,
	supportCss3:supportCss3,
	isElement:isElement,
	dataType:dataType,
	randomNum:randomNum

}
})();

2.使用

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src='./verification-code.js'></script>
</head>
<body>
	<div id='picCode'></div>
	<button id='refresh'>刷新验证码</button>
	<button id='getCode'>获取验证码</button>
<script>
var ww = verifiCode.picVerificationCode({
	num:5,//验证码个数
	iconum:20,//背景斑点个数
	fsize:[18,20,22,16],
	container:document.getElementById('picCode'),
	changeBtn:[document.getElementById('refresh')]

})
document.getElementById('getCode').addEventListener('click',function(){
	var data = verifiCode.getData()
	console.log(data)
},true)
</script>
</body>
</html>

3.效果图

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会尽力回答您的问题。针对您的问题,可以使用以下步骤实现: 1.在Vue3项目中,安装 `vue-recaptcha` 包,这个包实现了谷歌验证码功能。 2.在 `index.html` 文件中,引入次包需要的JS文件,如下所示: ```html <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script> ``` 其中 `reCAPTCHA_site_key` 是您在谷歌开发者网站上申请的Site key。 3.在 `App.vue` 中,添加如下代码: ```html <template> <div> <div ref="captcha"></div> <button @click="verify">Verify</button> </div> </template> <script> import { ref } from 'vue'; import { createRecaptcha } from 'vue-recaptcha'; export default { setup() { const captchaRef = ref(null); let captchaToken = null; // 创建recaptcha实例,并记录token createRecaptcha({ siteKey: 'reCAPTCHA_site_key', size: 'normal', container: captchaRef.value, badge: 'inline', callback: function (token) { captchaToken = token; }, }); function verify() { // 发送captchaToken 到后端进行验证 console.log(captchaToken); } return { captchaRef, verify }; }, }; </script> ``` 在 `createRecaptcha` 方法中,我们可以设置一些参数来指定验证码组件的属性,如 `siteKey`、`size`、`container`、`badge` 以及 `callback` 等等。这里的 `callback` 方法会在用户成功进行验证后被调用,返回一个token参数,可以在后端使用来验证验证码是否正确。 4.在后端中,通过接收到的 `captchaToken` 参数,向谷歌服务器发送请求来验证用户的验证码是否正确。如果正确,后端可以返回一个成功的信息给前端,否则返回一个失败的信息。 以上就是使用 `vue-recaptcha` 包来实现验证码验证的方法。希望对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值