canvas 模拟 验证码封装

1.今天给小伙伴利用 canvas 来给 jQuery 原型添加组件(必须引入jquery.js) :

  1. 页面Html,首先定义一个容器 拿来放canvas:

    
换一张

2.js封装:

/**
 * 功能: 登陆验证码生成器++————————
 * 时间:2018.7.2
 * auth:liangqiang
 */


(function ($, window, document) {

    var pluginName = "myCode";

    var defaults = {
        canvasId: "canvas", //canvas的ID
        width: "100", //默认canvas宽度
        height: "30", //默认canvas高度
        type: "blend",//图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
        code: "",
        clickRefresh:""//外部点击的容器 ID
    }

    function myFunction(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this.init();
    }






    myFunction.prototype = {

        constructor: myFunction,

        version: '1.0.0',

        init: function () {
            var that = this;
            var con = $(that.element);
            var canvas = document.createElement("canvas");
            that.settings.width = con.offsetWidth > 0 ? con.offsetWidth : "100";
            that.settings.height = con.offsetHeight > 0 ? con.offsetHeight : "30";
            canvas.id = that.settings.canvasId;
            canvas.width = that.settings.width;
            canvas.height = that.settings.height;
            canvas.style.cursor = "pointer";
            canvas.innerHTML = "您的浏览器版本不支持canvas";
            con.append(canvas);
            //需要盒子点击 和外部点击刷新  所以提到外面去
            that.refresh();
            //盒子点击
            canvas.addEventListener("click", function () {
                that.refresh();
            })
            //外部  点击  看不清 换一张
            var changeCanvas =  $(that.settings.clickRefresh );

            if(changeCanvas){
                changeCanvas.on("click", function () {
                    that.refresh();
                })
            }
            

        },
        //点击刷新
        refresh: function () {

            var ctx = "";
            var txtArr = null;
            if (canvas.getContext) {
                ctx = canvas.getContext('2d');
            } else {
                alert("你的浏览器不支持Canvas");
            }

            ctx.textBaseline = "middle";

            ctx.fillStyle = this.randomColor(180, 240);
            ctx.fillRect(0, 0, this.settings.width, this.settings.height);

            if (this.settings.type == "blend") { //判断验证码类型
                txtArr = this.numArr().concat(this.letterStr());
            } else if (this.options.type == "number") {
                txtArr = this.numArr();
            } else {
                txtArr = this.letterStr();
            }


            for (var i = 1; i <= 4; i++) {
                var txt = txtArr[this.randomNum(0, txtArr.length)];
                this.settings.code += txt;
                ctx.font = this.randomNum(this.settings.height / 2, this.settings.height) + 'px SimHei'; //随机生成字体大小
                ctx.fillStyle = this.randomColor(50, 160); //随机生成字体颜色       
                ctx.shadowOffsetX = this.randomNum(-3, 3);
                ctx.shadowOffsetY = this.randomNum(-3, 3);
                ctx.shadowBlur = this.randomNum(-3, 3);
                ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
                var x = this.settings.width / 5 * i;
                var y = this.settings.height / 2;
                var deg = this.randomNum(-30, 30);
                /**设置旋转角度和坐标原点**/
                ctx.translate(x, y);
                ctx.rotate(deg * Math.PI / 180);
                ctx.fillText(txt, 0, 0);
                /**恢复旋转角度和坐标原点**/
                ctx.rotate(-deg * Math.PI / 180);
                ctx.translate(-x, -y);
            }
            /**绘制干扰线**/
            for (var i = 0; i < 4; i++) {
                ctx.strokeStyle = this.randomColor(40, 180);
                ctx.beginPath();
                ctx.moveTo(this.randomNum(0, this.settings.width), this.randomNum(0, this.settings.height));
                ctx.lineTo(this.randomNum(0, this.settings.width), this.randomNum(0, this.settings.height));
                ctx.stroke();
            }
            /**绘制干扰点**/
            for (var i = 0; i < this.settings.width / 4; i++) {
                ctx.fillStyle = this.randomColor(0, 255);
                ctx.beginPath();
                ctx.arc(this.randomNum(0, this.settings.width), this.randomNum(0, this.settings.height), 1, 0, 2 * Math.PI);
                ctx.fill();
            }
        }
        ,
        /**生成一个随数字**/
        numArr: function () {
            var number = "0,1,2,3,4,5,6,7,8,9";
            return number.split(",");
        },
        /**生成字母数组**/
        letterStr: function () {
            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(",");
        },
        /**生成一个随机数**/
        randomNum: function (min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        },
        /**生成一个随机色**/
        randomColor: function (min, max) {
            var r = this.randomNum(min, max);
            var g = this.randomNum(min, max);
            var b = this.randomNum(min, max);
            return "rgb(" + r + "," + g + "," + b + ")";
        }
    }



    //向Jquery 注册 组件
    $.fn[pluginName] = function (options) {
        var e = this;
        e.each(function () {
            if (!$.data(this, pluginName)) {

                $.data(e, pluginName, new myFunction(e, options));
            }
        });
        return e;
    }
})(jQuery, window, document)



3.用法:

$(function(){
    //验证码验证
    $("#box").myCode({
        width:'100px',
        clickRefresh:".code"
    })



})

4.效果:


canvas 模拟 验证码封装_第1张图片
image.png

你可能感兴趣的:(canvas 模拟 验证码封装)