純JS實現圖片驗證碼功能併兼容IE6-8

使用方法

  使用特別簡單,定義一個DIV一驗證碼輸入框,引入下載的js插件,建立一個GVerify對象,參數能夠自定義一些或者傳入DIV的ID。這樣就生成了一驗證碼,效果見下圖1-1.html

複製代碼

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>圖形驗證碼</title>
    </head>
    <body>
        <div id="v_container" style="width: 200px;height: 50px;"></div>
        <input type="text" id="code_input" value="" placeholder="請輸入驗證碼"/><button id="my_button">驗證</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("驗證正確");
            }else{
                alert("驗證碼錯誤");
            }
        }    </script>
</html>

複製代碼

圖1-1canvas

   效果還不錯,大功告成。分分鐘搞定,在各個瀏覽器點了點都沒有撒問題。不過一到IE下面就GG了,IE9都還有用,IE8就沒有用了,只能看看它怎麼實現的了。因而我打開源碼,發現是canvas實現的,IE8如下不支持呀,這就尷尬了。而後我特地去看了看canvas這個元素的相關介紹,發現還真被我找到貓膩了。"咱們甚至能夠在 IE 中使用 <canvas> 標記,並在 IE 的 VML 支持的基礎上用開源的 JavaScript 代碼(由 Google 發起)來構建兼容性的畫布。 參見:http://excanvas.sourceforge.net/。",看到這一句我感受我有搞頭了,因而立刻下載了一個excanvas.js加載到頁面上,覺得添加一個js就能夠了,結果也是發現果真好使,正準備炫耀個人成果時,發現是IE11,不對勁呀!因而調整到IE8發現還不行,果真沒有想的這麼簡單。因而看了一遍插件源碼,木有發現問題呀,也不報錯。因而只能搜索看是什麼問題了。數組

改造

  查了一下資料發現是createelement()這個方法插件canvas在IE8如下也是不支持的,只能先在頁面寫上canvas元素。因而我改造了一下頁面,並把建立canvas的代碼修改成得到了。並把源代碼加了一部分註釋。使用方式變爲了以下:瀏覽器

複製代碼

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>圖形驗證碼</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="請輸入驗證碼"/><button id="my_button">驗證</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("驗證正確");
            }else{
                alert("驗證碼錯誤");
            }
        }    </script>
</html>

複製代碼

源碼作了以下修改(紅色的爲修改的部分)和註釋:app

複製代碼

!(function(window, document) {    function GVerify(options) { //建立一個圖形驗證碼對象,接收options對象爲參數
        this.options = { //默認options參數值
            id: "", //容器Id
            canvasId: "verifyCanvas", //canvas的ID
            width: "100", //默認canvas寬度
            height: "30", //默認canvas高度
            type: "blend", //圖形驗證碼默認類型blend:數字字母混合類型、number:純數字、letter:純字母
            code: ""
        }        
        if(Object.prototype.toString.call(options) == "[object Object]"){//判斷傳入參數類型
            for(var i in options) { //根據傳入的參數,修改默認參數值
                this.options[i] = options[i];
            }
        }else{//傳入單個對象就是id
            this.options.id = options;
        }        
        this.options.numArr = "0,1,2,3,4,5,6,7,8,9".split(",");//數字
        this.options.letterArr = getAllLetter();//生成字母數組
        this._init();//初始化
        this.refresh();//生成驗證碼    }

    GVerify.prototype = {        /**版本號**/
        version: '1.0.0',        
        /**初始化方法**/
        _init: function() {            var con = document.getElementById(this.options.id);//得到驗證碼的DIV
            var canvas = document.getElementById(this.options.canvasId);//得到畫布   IE不能支持canvas,能夠增長excanvas.js插件,可是仍是不支持createelement()的形式
            this.options.width = con.offsetWidth > 0 ? con.offsetWidth : "100";//若是有寬度就使用本身的,沒有就默認100
            this.options.height = con.offsetHeight > 0 ? con.offsetHeight : "30";//若是有長度就使用本身的,沒有就默認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(){//驗證碼點擊切換刷新                parent.refresh();
            }
        },        
        /**生成驗證碼**/
        refresh: function() {            this.options.code = "";//定義驗證碼爲""
            var canvas = document.getElementById(this.options.canvasId);//得到驗證碼畫布
            if(canvas.getContext) {//                var ctx = canvas.getContext('2d');//得到繪畫對象
            }else{//                return;
            }
            ctx.textBaseline = "middle";
            ctx.fillStyle = randomColor(180, 240);
            ctx.fillRect(0, 0, this.options.width, this.options.height);//繪製矩形  
            /* x:矩形起點橫座標(座標原點爲canvas的左上角,固然確切的來講是原始原點,後面寫到變形的時候你就懂了,如今暫時不用關係)
             y:矩形起點縱座標
             width:矩形長度
             height:矩形高度*/ 
            if(this.options.type == "blend") { //判斷驗證碼類型 blend:數字字母混合類型、number:純數字、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)];//取得一個字符
                this.options.code += txt;//鏈接驗證碼
                ctx.font = randomNum(this.options.height/2, this.options.height) + 'px SimHei'; //隨機生成字體大小
                ctx.fillStyle = randomColor(50, 160); //填充的樣式 隨機生成字體顏色        
                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);                /**設置旋轉角度和座標原點
                 * 
                 *  平移context.translate(x,y)
                 *    x:座標原點向x軸方向平移x
                 *    y:座標原點向y軸方向平移y
                 * 
                 * **/
                ctx.translate(x, y);
                ctx.rotate(deg * Math.PI / 180);//旋轉context.rotate(angle)
                ctx.fillText(txt, 0, 0);//context.fillText(text,x,y)  
                /**恢復旋轉角度和座標原點**/
                ctx.rotate(-deg * Math.PI / 180);
                ctx.translate(-x, -y);
            }            /**繪製干擾線**/
            for(var i = 0; i < 4; i++) {
                ctx.strokeStyle = randomColor(40, 180);//隨機顏色
                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();
            }            /**繪製干擾點**/
            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();
            }
        },        
        /**驗證驗證碼**/
        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;
            }
        }
    }    /**生成字母數組**/
    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(",");
    }    /**生成一個隨機數**/
    function randomNum(min, max) {        return Math.floor(Math.random() * (max - min) + min);
    }    /**生成一個隨機色**/
    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;//設置爲window對象})(window, document);

複製代碼

總結

  一、要支持IE的canvas要引入wxcanvas.js並修改源碼爲獲取canvas元素。dom

  二、在html中要加上div和canvas元素。ide

  在秀一波個人驗證碼,哈哈字體

相關文章
相關標籤/搜索