純JS實(shí)現(xiàn)圖片驗(yàn)證碼功能并兼容IE6-8(推薦)
最近要搞一個(gè)圖片驗(yàn)證碼功能,但是又不想自己寫后臺(tái)代碼。于是自己準(zhǔn)備搞一個(gè)純前端的驗(yàn)證碼功能,于是網(wǎng)上搜索了一下,找到一個(gè)插件gVerify.js,簡單好用,實(shí)現(xiàn)完美。不過后面接到說要兼容IE8,想想也是醉了。萬惡的IE,不過也還好,也沒有想著在去找插件,準(zhǔn)備自己搞一搞,順便拿來學(xué)習(xí)一下并加強(qiáng)自己的知識(shí)。下面看我是如何搞定它的,雖然花了一點(diǎn)時(shí)間,不過也值得。
使用方法
使用特別簡單,定義一個(gè)DIV一驗(yàn)證碼輸入框,引入下載的js插件,創(chuàng)建一個(gè)GVerify對(duì)象,參數(shù)可以自定義一些或者傳入DIV的ID。這樣就生成了一驗(yàn)證碼,效果見下圖1-1.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>圖形驗(yàn)證碼</title> </head> <body> <div id="v_container" style="width: 200px;height: 50px;"></div> <input type="text" id="code_input" value="" placeholder="請(qǐng)輸入驗(yàn)證碼"/><button id="my_button">驗(yàn)證</button> </body> <script src="js/gVerify.js"></script> <script> var verifyCode = new GVerify("v_container"); document.getElementById("my_button").onclick = function(){ var res = verifyCode.validate(document.getElementById("code_input").value); if(res){ alert("驗(yàn)證正確"); }else{ alert("驗(yàn)證碼錯(cuò)誤"); } } </script> </html>
圖1-1
效果還不錯(cuò),大功告成。分分鐘搞定,在各個(gè)瀏覽器點(diǎn)了點(diǎn)都沒有撒問題。不過一到IE下面就GG了,IE9都還有用,IE8就沒有用了,只能看看它怎么實(shí)現(xiàn)的了。于是我打開源碼,發(fā)現(xiàn)是canvas實(shí)現(xiàn)的,IE8以下不支持呀,這就尷尬了。然后我特意去看了看canvas這個(gè)元素的相關(guān)介紹,發(fā)現(xiàn)還真被我找到貓膩了。"我們甚至可以在 IE 中使用 <canvas> 標(biāo)記,并在 IE 的 VML 支持的基礎(chǔ)上用開源的 JavaScript 代碼(由 Google 發(fā)起)來構(gòu)建兼容性的畫布。 參見:
改造 查了一下資料發(fā)現(xiàn)是createelement()這個(gè)方法插件canvas在IE8以下也是不支持的,只能先在頁面寫上canvas元素。于是我改造了一下頁面,并把創(chuàng)建canvas的代碼修改為獲得了。并把源代碼加了一部分注釋。使用方式變?yōu)榱巳缦拢?/p>
源碼做了如下修改(紅色的為修改的部分)和注釋: 總結(jié) 1、要支持IE的canvas要引入wxcanvas.js并修改源碼為獲取canvas元素。 2、在html中要加上div和canvas元素。 在秀一波我的驗(yàn)證碼,哈哈 以上所述是小編給大家介紹的純JS實(shí)現(xiàn)圖片驗(yàn)證碼功能并兼容IE6-8(推薦),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖形驗(yàn)證碼</title>
</head>
<body>
<div id="v_container" style="width: 100px;height: 40px;position: relative;top: -61px;left: 230px;">
<canvas id="verifyCanvas" width="100" height="40" style="cursor: pointer;"></canvas>
</div>
<input type="text" id="code_input" value="" placeholder="請(qǐng)輸入驗(yàn)證碼"/><button id="my_button">驗(yàn)證</button>
</body>
<script src="js/gVerify.js"></script>
<script>
var verifyCode = new GVerify("v_container");
document.getElementById("my_button").onclick = function(){
var res = verifyCode.validate(document.getElementById("code_input").value);
if(res){
alert("驗(yàn)證正確");
}else{
alert("驗(yàn)證碼錯(cuò)誤");
}
}
</script>
</html>
!(function(window, document) {
function GVerify(options) { //創(chuàng)建一個(gè)圖形驗(yàn)證碼對(duì)象,接收options對(duì)象為參數(shù)
this.options = { //默認(rèn)options參數(shù)值
id: "", //容器Id
canvasId: "verifyCanvas", //canvas的ID
width: "100", //默認(rèn)canvas寬度
height: "30", //默認(rèn)canvas高度
type: "blend", //圖形驗(yàn)證碼默認(rèn)類型blend:數(shù)字字母混合類型、number:純數(shù)字、letter:純字母
code: ""
}
if(Object.prototype.toString.call(options) == "[object Object]"){//判斷傳入?yún)?shù)類型
for(var i in options) { //根據(jù)傳入的參數(shù),修改默認(rèn)參數(shù)值
this.options[i] = options[i];
}
}else{//傳入單個(gè)對(duì)象就是id
this.options.id = options;
}
this.options.numArr = "0,1,2,3,4,5,6,7,8,9".split(",");//數(shù)字
this.options.letterArr = getAllLetter();//生成字母數(shù)組
this._init();//初始化
this.refresh();//生成驗(yàn)證碼
}
GVerify.prototype = {
/**版本號(hào)**/
version: '1.0.0',
/**初始化方法**/
_init: function() {
var con = document.getElementById(this.options.id);//獲得驗(yàn)證碼的DIV
var canvas = document.getElementById(this.options.canvasId);//獲得畫布 IE不能支持canvas,可以增加excanvas.js插件,但是還是不支持createelement()的形式
this.options.width = con.offsetWidth > 0 ? con.offsetWidth : "100";//如果有寬度就使用自己的,沒有就默認(rèn)100
this.options.height = con.offsetHeight > 0 ? con.offsetHeight : "30";//如果有長度就使用自己的,沒有就默認(rèn)30
// canvas.id = this.options.canvasId;//為兼容IE把這些去掉
// canvas.width = this.options.width;
// canvas.height = this.options.height;
// canvas.style.cursor = "pointer";
// canvas.innerHTML = "您的瀏覽器版本不支持canvas";
// con.appendChild(canvas);
var parent = this;//把this賦值parent
canvas.onclick = function(){//驗(yàn)證碼點(diǎn)擊切換刷新
parent.refresh();
}
},
/**生成驗(yàn)證碼**/
refresh: function() {
this.options.code = "";//定義驗(yàn)證碼為""
var canvas = document.getElementById(this.options.canvasId);//獲得驗(yàn)證碼畫布
if(canvas.getContext) {//
var ctx = canvas.getContext('2d');//獲得繪畫對(duì)象
}else{//
return;
}
ctx.textBaseline = "middle";
ctx.fillStyle = randomColor(180, 240);
ctx.fillRect(0, 0, this.options.width, this.options.height);//繪制矩形
/* x:矩形起點(diǎn)橫坐標(biāo)(坐標(biāo)原點(diǎn)為canvas的左上角,當(dāng)然確切的來說是原始原點(diǎn),后面寫到變形的時(shí)候你就懂了,現(xiàn)在暫時(shí)不用關(guān)系)
y:矩形起點(diǎn)縱坐標(biāo)
width:矩形長度
height:矩形高度*/
if(this.options.type == "blend") { //判斷驗(yàn)證碼類型 blend:數(shù)字字母混合類型、number:純數(shù)字、letter:純字母
var txtArr = this.options.numArr.concat(this.options.letterArr);
} else if(this.options.type == "number") {
var txtArr = this.options.numArr;
} else {
var txtArr = this.options.letterArr;
}
for(var i = 1; i <= 4; i++) {
var txt = txtArr[randomNum(0, txtArr.length)];//取得一個(gè)字符
this.options.code += txt;//連接驗(yàn)證碼
ctx.font = randomNum(this.options.height/2, this.options.height) + 'px SimHei'; //隨機(jī)生成字體大小
ctx.fillStyle = randomColor(50, 160); //填充的樣式 隨機(jī)生成字體顏色
ctx.shadowOffsetX = randomNum(-3, 3);//陰影的橫向位移量
ctx.shadowOffsetY = randomNum(-3, 3);//陰影的縱向位移量
ctx.shadowBlur = randomNum(-3, 3);//陰影的模糊范圍(值越大越模糊)
ctx.shadowColor = "rgba(0, 0, 0, 0.3)";//陰影的顏色
var x = this.options.width / 5 * i;
var y = this.options.height / 2;
var deg = randomNum(-30, 30);
/**設(shè)置旋轉(zhuǎn)角度和坐標(biāo)原點(diǎn)
*
* 平移context.translate(x,y)
* x:坐標(biāo)原點(diǎn)向x軸方向平移x
* y:坐標(biāo)原點(diǎn)向y軸方向平移y
*
* **/
ctx.translate(x, y);
ctx.rotate(deg * Math.PI / 180);//旋轉(zhuǎn)context.rotate(angle)
ctx.fillText(txt, 0, 0);//context.fillText(text,x,y)
/**恢復(fù)旋轉(zhuǎn)角度和坐標(biāo)原點(diǎn)**/
ctx.rotate(-deg * Math.PI / 180);
ctx.translate(-x, -y);
}
/**繪制干擾線**/
for(var i = 0; i < 4; i++) {
ctx.strokeStyle = randomColor(40, 180);//隨機(jī)顏色
ctx.beginPath();//路徑 context.beginPath()
ctx.moveTo(randomNum(0, this.options.width), randomNum(0, this.options.height));//繪制線段 context.moveTo(x,y) context.lineTo(x,y)
ctx.lineTo(randomNum(0, this.options.width), randomNum(0, this.options.height));
ctx.stroke();
}
/**繪制干擾點(diǎn)**/
for(var i = 0; i < this.options.width/4; i++) {
ctx.fillStyle = randomColor(0, 255);
ctx.beginPath();
ctx.arc(randomNum(0, this.options.width), randomNum(0, this.options.height), 1, 0, 2 * Math.PI);// 圓弧context.arc(x, y, radius, starAngle,endAngle, anticlockwise)
ctx.fill();
}
},
/**驗(yàn)證驗(yàn)證碼**/
validate: function(code){
var code = code.toLowerCase();
var v_code = this.options.code.toLowerCase();
//console.log(v_code);
if(code == v_code){
return true;
}else{
this.refresh();
return false;
}
}
}
/**生成字母數(shù)組**/
function getAllLetter() {
var letterStr = "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,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";
return letterStr.split(",");
}
/**生成一個(gè)隨機(jī)數(shù)**/
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
/**生成一個(gè)隨機(jī)色**/
function randomColor(min, max) {
var r = randomNum(min, max);
var g = randomNum(min, max);
var b = randomNum(min, max);
return "rgb(" + r + "," + g + "," + b + ")";
}
window.GVerify = GVerify;//設(shè)置為window對(duì)象
})(window, document);
相關(guān)文章
JavaScript設(shè)置獲取和設(shè)置屬性的方法
這篇文章主要介紹了JavaScript設(shè)置獲取和設(shè)置屬性的方法,學(xué)會(huì)使用getAttribute、setAttribute的用法,需要的朋友可以參考下2015-03-03location.search在客戶端獲取Url參數(shù)的方法
最近一直在寫html,剛接觸到,感覺挺復(fù)雜的。。比如傳參,在.net里可以直接用Request接受,而在html中還要經(jīng)過處理,找了一些資料,寫了個(gè)方法。2010-06-06淺談函數(shù)調(diào)用的不同方式,以及this的指向
下面小編就為大家?guī)硪黄獪\談函數(shù)調(diào)用的不同方式,以及this的指向。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09JS實(shí)現(xiàn)字符串轉(zhuǎn)日期并比較大小實(shí)例分析
這篇文章主要介紹了JS實(shí)現(xiàn)字符串轉(zhuǎn)日期并比較大小的方法,以實(shí)例形式較為詳細(xì)分析了JavaScript字符串與日期操作的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-12-12